3 ms·
That's kind of what generator expressions are actually :) https://www.python.org/dev/peps/pep-0289/ https://www.python.org/dev/peps/pep-0289/ You can pass the
by th 11y ago
That's kind of what generator expressions are actually :)
https://www.python.org/dev/peps/pep-0289/ 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 https://youtu.be/u-mhKtC1Xh4?t=35m05s
- icebraining 11y agoTo 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'>
- Grue3 11y ago>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.
- sanderjd 11y agoExcellent. Mental model of what python can do: changed. I sort of thought that was a fancy python 3 feature, but looks like python 2 has it as well.