Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to an empty list using a single line for-loop python

I am trying to append numbers from a generator to an empty list using a single line for loop but it returns None. I understand it can be done using a for loop with 2 lines but I was wondering what I am missing. i.e.,

>>> [].append(i) for i in range(10)

[None, None, None, None, None, None, None, None, None, None]

I was hoping to create this in one line:

>>> [].append(i) for i in range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Thank you.

like image 603
Nikki Mino Avatar asked Jan 29 '15 04:01

Nikki Mino


People also ask

How do you append a list in Python with one line?

append(x) method—as the name suggests—appends element x to the end of the list . In the first line of the example, you create the list l . You then append the integer element 42 to the end of the list. The result is the list with one element [42] .

Can you append to an empty list Python?

You can add elements to an empty list using the methods append() and insert() : append() adds the element to the end of the list. insert() adds the element at the particular index of the list that you choose.

How do you append to a list in a for loop in Python?

You can append a list in for loop, Use the list append() method to append elements to a list while iterating over the given list.

Can you append to list while loop Python?

Use the Python List append() method to append elements to a list while iterating over the list using a for-in loop. If you append a new element to the list while iterating the list results in a list containing the original list's elements and the new elements.


1 Answers

Write a proper comprehension, without append.

>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(i for i in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
like image 143
Terry Jan Reedy Avatar answered Nov 15 '22 15:11

Terry Jan Reedy