Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-line for loop as a function argument

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)
like image 293
Qback Avatar asked Mar 07 '23 04:03

Qback


2 Answers

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.

like image 90
Tim Pietzcker Avatar answered Mar 19 '23 12:03

Tim Pietzcker


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

like image 35
kabanus Avatar answered Mar 19 '23 13:03

kabanus