80

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)

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
0100110010101
  • 6,469
  • 5
  • 33
  • 38

5 Answers5

140

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
  • 390,455
  • 97
  • 512
  • 589
  • I'm still a beginner with Python, what's the purpose of this: "2*a"? @Adam Rosenfield – Ahmad Feb 16 '22 at 10:27
  • 1
    @Ahmad A bit late, but hopefully it can help someone else. `a` gets assigned every element in the list `x` (because the for loop). So, the `2*a` is simply just taking every element in the list x and multiplying it by two. The doubled values will be in `y` after it's done iterating through the entire list `x` – Hasnain Ali Apr 20 '22 at 16:59
34
for item in array: array2.append (item)

Or, in this case:

array2 += array
liori
  • 40,917
  • 13
  • 78
  • 105
4

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
  • 27,179
  • 15
  • 70
  • 84
3

If you're trying to copy the array:

array2 = array[:]
a paid nerd
  • 30,702
  • 30
  • 134
  • 179
3

Even array2.extend(array1) will work.

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
Prabhu
  • 3,434
  • 8
  • 40
  • 48