Re:Python List Comprehensions Explained Visually
by icebraining on Wednesday December 02, 2015 @07:53PM
(#10667013)
To make it even more clear, you can store the generator in a variable and pass it around:
>>> x = (a*a for a in range(3))
>>> type(x)
<type 'generator'>
Re:Python List Comprehensions Explained Visually
by Grue3 on Thursday December 03, 2015 @07:15AM
(#10669180)
>Same thing passed to list and set constructors (which you'd never do because we have the special comprehension syntax for those
I do this all the time (for set) because it works even in python 2.6. Also dict((key, value) for foo in bar). In fact, I think it was a bad idea to add special comprehension syntax for sets and dicts.
https://www.python.org/dev/peps/pep-0289/
You can pass them into anything that expects an iterable. That's pretty much the same since iterable types will frequently consume an iterable in their constructor.
For example, here's a "tuple comprehension" (really just a generator expression passed to a tuple):
>>> tuple(x for x in [1, 2, 3])
Same thing passed to list and set constructors (which you'd never do because we have the special comprehension syntax for those:
>>> list(x for x in [1, 2, 3])
>>> set(x for x in [1, 2, 3])
I explained these in a very slightly different way in the linked webinar I linked in the post: https://youtu.be/u-mhKtC1Xh4?t=35m05s