Reputation: 10219
I found both of them will output the expected result 2
.
max([a for a in [1,2]])
is max()
+ list comprehension
, an easy one.
max(a for a in [1,2])
is max()
+ ?
. Why does it work? What do we name the structure a for a in [1,2]
?
A generator is in form of (a for a in [1,2])
. I doubt that the (a for a in [1,2])
insides max(a for a in [1,2])
is a generator. However, if that's the case, why can a pair of ()
be ignored? Technically speaking it should be max((a for a in [1,2]))
.
Thanks.
Upvotes: 3
Views: 68
Reputation: 45806
That is in fact a generator expression. Generator expressions can make use of the ()
from argument lists; providing that they're the only argument passed to the function. If there are more arguments, they require their own pair of parenthesis.
You can verify this yourself with a quick test:
def func(arg):
print(type(arg))
func(n for n in range(10)) # Prints <class 'generator'>
From PEP 289:
The syntax requires that a generator expression always needs to be directly inside a set of parentheses and cannot have a comma on either side. . . . [I]f a function call has a single positional argument, it can be a generator expression without extra parentheses, but in all other cases you have to parenthesize it.
Upvotes: 6