52
votes

I'm not sure if I need a lambda, or something else. But still, I need the following:

I have an array = [1,2,3,4,5]. I need to put this array, for instance, into another array. But write it all in one line.

for item in array:
    array2.append(item)

I know that this is completely possible to iterate through the items and make it one-line. But googling and reading manuals didn't help me that much... if you can just give me a hint or name this thing so that I could find what that is, I would really appreciate it.

Update: let's say this: array2 = SOME FANCY EXPRESSION THAT IS GOING TO GET ALL THE DATA FROM THE FIRST ONE

(the example is NOT real. I'm just trying to iterate through different chunks of data, but that's the best I could come up with)

5
"But write it all in one line." ... Why? The program does not get better because you use less lines. - Lennart Regebro
extremely funny. i'm trying to learn the language. and you're being buggy. THIS EXAMPLE IS NOT REAL, man. - 0100110010101
@opetrov: Being rude to people who are asking for clarification doesn't do much except stop people from wanting to help you. DON'T BE RUDE, man. - Ken White
@ken it wasn't the question. it was a statement. @lennart why not to do it in one line if the language supports that? why do Lambdas & functional extensions? - 0100110010101
@lennart in ur blog you say that python has list comprehesions. you claim it is good or no? if yes, that's the reason, why i was asking. i want to use everything the language can give. sorry for shouting thou. really didn't mean it. subscribed 2 ur blog. thx - 0100110010101

5 Answers

92
votes

The keyword you're looking for is list comprehensions:

>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]
23
votes
for item in array: array2.append (item)

Or, in this case:

array2 += array
2
votes

If you're trying to copy the array:

array2 = array[:]
2
votes

If you really only need to add the items in one array to another, the '+' operator is already overloaded to do that, incidentally:

a1 = [1,2,3,4,5]
a2 = [6,7,8,9]
a1 + a2
--> [1, 2, 3, 4, 5, 6, 7, 8, 9]
2
votes

Even array2.extend(array1) will work.