How can I use a Python for loop in one line?
I’m looking for a way to iterate through an array and append its items to another array, all in one line. For example, I have this array:
array = [1, 2, 3, 4, 5]
And I want to add its items to another array like this:
for item in array:
array2.append(item)
I know it’s possible to do this in one line, but I’m not sure if I should use a lambda or something else. I’ve tried reading the manuals and googling it, but couldn’t find a clear answer. Could you provide a hint or the correct syntax for this? Specifically, I want to achieve this:
array2 = SOME FANCY EXPRESSION THAT WILL GET ALL THE DATA FROM THE FIRST ARRAY
The example may not be realistic, but it’s just to show the kind of iteration I’m trying to perform. What is the best way to write this Python for loop in one line?
List Comprehension is such a clean and concise way to work with arrays. For instance, you can iterate through an array and append its items to another array in just one line:
array = [1, 2, 3, 4, 5]
array2 = [item for item in array]
It’s quick, readable, and Pythonic!
Building on @joe-elmoufak point, another way to achieve the same result is by using the extend()
method. It’s equally concise and directly adds all elements from one array to another:
array = [1, 2, 3, 4, 5]
array2 = []
array2.extend(array)
Simple, right? And you don’t need to create a new array explicitly—just extend an existing one.
Great suggestions, @joe-elmoufak and @netra.agarwal! Let me add another approach using the map()
function. It’s perfect if you want to iterate over the array and even apply transformations while copying:
array = [1, 2, 3, 4, 5]
array2 = list(map(lambda item: item, array))
While map()
works similarly, it opens up additional possibilities for inline processing.