Reputation: 1
I'm trying to understand why these two examples are giving me different outputs.
Example1:
list1 = [1,2,3,4,5]
list2 = []
for l in list1:
list2.append(l)
print list2
#[1, 2, 3, 4, 5]
Example2:
list1 = [1,2,3,4,5]
list2 = []
list2.append(l for l in list1)
print list2
#[<generator object <genexpr> at 0x10379ecd0>]
I've tried putting list() or tuple() after the append in the second example, but it's giving me one single element in the new list as opposed to 5 different ones.
list2.append(tuple(l for l in list1))
#[(1, 2, 3, 4, 5)]
Would there be a way for me to get same same output from Example1 using just one line for the for loop?
I'd really appreciate any help!
Upvotes: 0
Views: 58
Reputation: 9846
(l for l in list1)
is a generator expression. It explicitly returns a generator, which is essentially a memory-saving iterator (think a list, but with each element returned on the fly, rather than stored all in memory). The key to realising it is a generator expression is in noting that the expression is surrrounded by (
and )
.
In list2.append(l for l in list1)
, you have appended a single generator to the empty list. You can still get all the elements you want by doing for element in list2[0]
, but it is not the same thing.
However, in doing
for l in list1:
list2.append(l)
no such generator expressions are encountered. At every iteration - every run of the loop - l
, an element, is appended to the end. Hence why this works the way you think.
If you want to get your list2
using something similar to the generator expression, you want to use a list comprehension instead:
list2 = [l for l in list1]
Note that the difference between the structure of a list comprehension and a generator expression is simply the presence of square brackets [
,]
rather than parentheses.
Upvotes: 3
Reputation: 22954
If you don't like the nested list then you may simply use :
list1 = [1,2,3,4,5]
list2 = []
[list2.append(l) for l in list1]
Upvotes: 0
Reputation: 729
You don't want to use append in the second example. Instead you want
list2 = [l for l in list1]
There are easier ways to copy a list, but this is the one that most closely matches what you're going for in Example 2.
Upvotes: 0
Reputation: 304137
You need extend
instead of append
for the second example
list1 = [1,2,3,4,5]
list2 = []
list2.extend(l for l in list1) # or just list2.extend(list1)
print list2
If all you want to do is copy list1
then
list2 = list1[:]
or
list2 = list(list1)
will do it
Upvotes: 4