Python Forum

Full Version: Simple list comprehension misunderstanding
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
a = [1,4,9,16,25,36,49,64,81,100]
print(list(a[x] for x in range(6)))


gives me [1, 4, 9, 16, 25, 36] whereas

a = [1,4,9,16,25,36,49,64,81,100]
print(a[x] for x in range(6))
gives me <generator object <genexpr> at 0x030A8BB0>

What exactly is the latter error and why does it occur?
it's not an error.
(a[x] for x in range(6)) is generator expression that returns iterator. when you pass it as argument to function like print() you can omit the brackets to same effect.
In the first example you use list() to convert the same generator to a list
(Oct-10-2019, 06:41 PM)buran Wrote: [ -> ]it's not an error.
(a[x] for x in range(6)) is generator expression that returns iterator. when you pass it as argument to function like print() you can omit the brackets to same effect.
In the first example you use list() to convert the same generator to a list

So in the first example it prints out the list, and in the second example it prints out what it is--which is a generator object (with iterating rule stored in memory address 0x030A8BB0, maybe?)?
yes, the list being produced from converting the same generator expression