Use `for` in `print()` will give a generator on Python 3.x? -
why , how works? example i'm writing list comprehension this:
>>> = (10, 30, 20) >>> print([q q in a]) [10, 30, 20]
at now, if remove []
, work, but:
>>> = (10, 30, 20) >>> print(q q in a) <generator object <genexpr> @ 0x7fe527d1dca8>
does python make generator here? , if without print()
:
>>> = (10, 30, 20) >>> b = q q in file "<input>", line 1 b = q q in ^ syntaxerror: invalid syntax
i'm thinking because (q q in a)
make generator, that's impossible, i'm not using 2 pair of ()
like:
>>> = (10, 30, 20) >>> print((q q in a)) # here 2 pair of `()` <generator object <genexpr> @ 0x7fe527d1dca8>
does python make generator here?
yes. quoting official documentation of generator expressions,
the parentheses can omitted on calls 1 argument.
note exception actual syntax
generator_expression ::= "(" expression comp_for ")"
so, when did
b = q q in
python not able parse it, not valid python expression. why getting syntaxerror
.
if wanted print elements generator expression, can unpack result of print
function, suggested blckknght, this
>>> = (10, 30, 20) >>> print(*(q q in a)) 10 30 20
Comments
Post a Comment