def strange_syntax(stuff):
return ".".join(item for item in stuff)
How (and why) works this code? What happens here? Normally I can't use this syntax. Also, this syntax doesn't exist if it's not inside some function as an argument.
I know, I could do the same with:
def normal_syntax(stuff):
return ".".join(stuff)
This is called a generator expression.
It works just like a list comprehension (but evaluating the iterated objects lazily and not building a new list from them), but you use parentheses instead of brackets to create them. And you can drop the parentheses in a function call that only has one argument.
In your specific case, there is no need for a generator expression (as you noted) - (item for item in stuff)
gives the same result as stuff
. Those expressions start making sense when doing something with the items like (item.strip() for item in stuff)
(map) or (item for item in stuff if item.isdigit())
(filter) etc.
When used in a function call, the syntax:
f(a for a in b)
implicitly is compiled as a generator, meaning
f((a for a in b))
This is just syntactic sugar, to make the program look nicer. It doesn't make much sense to write directly in the console
>>>a for a in b
because it's unclear if you want to create a generator, or perform a regular loop. In this case you must use the outer ()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With