I was just experimenting in Python with different syntax for passing in a generator as an argument to a function, and I realized that although I've been doing this,
>>> sum((j for j in xrange(5)))
10
this works as well:
>>> sum(j for j in xrange(5))
10
This is tested on Python 2.6.6 on Linux. What's going on under the hood? Is it just syntactic sugar? After all, usually an unwrapped generator is indecipherable to the interpreter:
>>> j for j in xrange(5)
File "<stdin>", line 1
j for j in xrange(5)
^
SyntaxError: invalid syntax
sum(j for j,k in {'a':1, 'b':2}.iteritems())
. How is the comma between thej
andk
interpreted, and why? – Castellatedprint False,True or True,False
– Petulafor
) is relatively common, so requiring parens on it would be rather cumbersome. (For the former: After seeing the start of a generator expression, the parser expects an identifier or some comma-seperated identifiers - what comes next qualifies as such, so it goes with that) – Patrinapatriot