dspjm dspjm - 6 months ago 11
Python Question

Python: what does a comprehension in a set() mean?

I saw something like:

set(x for x in [1, 2, 3])


I know
x for x in [1, 2, 3]
is a comprehension, but I cannot find a valid grammar for it, since
x for x in [1, 2, 3]
itself is invalid.

Answer

From python3 reference

call ::=  primary "(" [argument_list [","] | comprehension] ")"
comprehension ::=  expression comp_for

check:

set(x for x in [1, 2, 3])

set is primary, x is expression and for x in [1, 2, 3] is comp_for