Python Forum
Simple list comprehension misunderstanding - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Simple list comprehension misunderstanding (/thread-21704.html)



Simple list comprehension misunderstanding - Mark17 - Oct-10-2019

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?


RE: Simple list comprehension misunderstanding - buran - Oct-10-2019

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


RE: Simple list comprehension misunderstanding - Mark17 - Oct-10-2019

(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?)?


RE: Simple list comprehension misunderstanding - buran - Oct-10-2019

yes, the list being produced from converting the same generator expression