Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use python generator expressions to create a oneliner to run a function multiple times and get a list output

I am wondering if there is there is a simple Pythonic way (maybe using generators) to run a function over each item in a list and result in a list of returns?

Example:

def square_it(x):
    return x*x

x_set = [0,1,2,3,4]
squared_set = square_it(x for x in x_set)

I notice that when I do a line by line debug on this, the object that gets passed into the function is a generator.

Because of this, I get an error: TypeError: unsupported operand type(s) for *: 'generator' and 'generator'

I understand that this generator expression created a generator to be passed into the function, but I am wondering if there is a cool way to accomplish running the function multiple times only by specifying an iterable as the argument? (without modifying the function to expect an iterable).

It seems to me that this ability would be really useful to cut down on lines of code because you would not need to create a loop to fun the function and a variable to save the output in a list.

Thanks!

like image 319
Pswiss87 Avatar asked Dec 14 '25 12:12

Pswiss87


1 Answers

You want a list comprehension:

squared_set = [square_it(x) for x in x_set]
like image 166
BrenBarn Avatar answered Dec 17 '25 08:12

BrenBarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!