tags:

views:

165

answers:

5

Hi!

I'm not sure if i need lamda, or something else. But still, i need 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.

Python geeks, pls help)

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

(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  A: 
for item in array: array2.append (item)

Or, in this case:

array2 += array
liori
brilliant :) i will probably need to change the question)
ifesdjeen
+8  A: 

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]
Adam Rosenfield
actually, yes! that's what i was looking for!!)can you tell me how this thing is called so that i could read more about other possibilities and operators as well?)
ifesdjeen
thank you so much!
ifesdjeen
BTW, you may also know the following:i have an object: a = { "id": 1, "smth": 2 }i need to add a property to it with a name "smth2", so that my a would be: a = { "id": 1, "smth": 2, "smth2": 3 }
ifesdjeen
nm it's dictionary. i've figured it out.
ifesdjeen
+1  A: 

If you're trying to copy the array:

array2 = array[:]
a paid nerd
+1  A: 

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]
ewall
A: 

Even array2.extend(array1) will work

Prabhu