Search code examples
pythonpython-3.xsyntaxgenerator-expression

Using comprehensions in arguments


Consider this:

>>> set((x,y) for x in range(1,3) for y in range(1,3))                                                                                                                                                            
{(1, 1), (1, 2), (2, 1), (2, 2)}

However, if I just take the argument I used above:

>>> (x,y) for x in range(1,3) for y in range(1,3)

I get SyntaxError

What exactly does set get in my first call? An object? An expression? Are they different things?

Technically speaking, set expects at most 1 argument, so I don't understand how the first expression works but the second one doesn't.


Solution

  • A generator expression has outer parentheses, but it is permitted to omit them when it is the sole argument of a function. Omitting the outer parentheses in this situation is no more than syntactic sugar.

    So the expression:

    set((x,y) for x in range(1,3) for y in range(1,3))
    

    is exactly the same as:

    set(((x,y) for x in range(1,3) for y in range(1,3)))