4 ms·
This is part of the generalized comprehension syntax. You can also do lazy generator comprehensions. a = (i for i in range(10) if i % 2 == 0) print(lis
by rectangletangle 11y ago
This is part of the generalized comprehension syntax. You can also do lazy generator comprehensions.
a = (i for i in range(10) if i % 2 == 0)
print(list(a))
You can omit the parenthesis, and use them in calls which expect an iterable.
b = max(i for i in range(0, 10) if i % 2 == 0)
print(b)
- delluminatus 11y agoIt's not exactly the same, which is what I thought was interesting. My first example did use a generator expression inside the dict() constructor, but in that case you need to specify the key and value in a tuple or a list. With the dictionary comprehension you can just separate the key and value with a colon, which is more natural. It might just be sugar on top of a generator expression but it is definitely a special case, syntactically speaking.
- aaronchall 11y agoYes, in Python 2.7 onward: s = {i**2 for i in range(10) if i} and the colon is what makes the dict comprehension different from the set comprehension: d - {i:i**2 for i in range(10) if i}
- aaronchall 11y agoAlthough Raymond Hettinger has also called them generator "comprehensions" in the early proposals, the current documentation calls them "generator expressions". And good examples. Here's how you make those set/dict whatever comprehensions in Python 2.6, before the native syntax is used: s = set(i for i in xrange(10) if not i%2)
- rectangletangle 11y agoSeems like a comprehension is just a particular form of Python expression.
- aaronchall 11y agoHere's the grammar file: https://docs.python.org/2/reference/grammar.html https://docs.python.org/2/reference/grammar.html Look for dictorsetmaker (for {}) testlist_comp (for generator expressions) and listmaker (for [], i.e. list comprehensions).