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.
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] .
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With