3

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.

guo
  • 9,674
  • 9
  • 41
  • 79
  • 1
    Actually easy to find out what it is if you replace `max` with `print`. – Wups Oct 19 '20 at 13:30
  • What is your python version? This seems to be a bug fixed since then: https://docs.python.org/3.6/whatsnew/3.5.html#changes-in-python-behavior – nocibambi Oct 19 '20 at 13:31
  • Does this answer your question? [Generator as function argument](https://stackoverflow.com/questions/32521140/generator-as-function-argument) – nocibambi Oct 19 '20 at 13:31
  • @nocibambi it's not a bug if it's a single argument. – bereal Oct 19 '20 at 13:32
  • 1
    @nocibambi The bug was allowing multi-argument calls to not have their own pair: "Python 3.5 now correctly raises a SyntaxError, as generator expressions must be put in parentheses if not a sole argument to a function." – Carcigenicate Oct 19 '20 at 13:34

1 Answers1

6

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.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117