Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignments in python list comprehension

I am looking for a way to do assignments in a list comprehension. I would like to rewrite something like the following piece of code into a list comprehension.

I have this "costly" function:

import time
def f(x):
    time.sleep(1)
    return x + 1

And this loop:

l = []
for value in [1, 2, 3]:
    x = f(value)
    l.append(x + x)

I would like to rewrite this to a list comprehension:

l = [
     f(value) + f(fvalue)
     for value in [1, 2, 3]
]

But since calling f(value) is costly, I would like to minimize the number of calls (this following snippet doesn't run):

l = [
     (x = f(value))
     x + x
     for value in [1, 2, 3]
]

I've read about the assignment expression (:=) (https://www.python.org/dev/peps/pep-0572/#changing-the-scope-rules-for-comprehensions) but I can't seem to figure it out.

like image 854
Steven Avatar asked Mar 29 '26 16:03

Steven


1 Answers

My approach would be to nest multiple list comprehension, like

l_new = [x * x * y for x, y in [f(value) for value in [1, 2, 3]]]

So f() should only be called once for each value.

like image 108
Lootcifer Avatar answered Mar 31 '26 06:03

Lootcifer



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!