Josh
Josh

Reputation: 12791

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.

Upvotes: 1

Views: 100

Answers (1)

alani
alani

Reputation: 13079

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)))

Upvotes: 6

Related Questions