'List iteration with substitution into one-liner
I want to turn the following for loop:
n = 10
x0 = 0
values = [x0]
for i in range(n):
x0 = f(x0)
values.append(x0)
into a one liner. I figured I could do something like this:
values = [f(x0) for i in range(n)]
but I need to update the value of x0 in each instance of the loop. Any ideas?
Solution 1:[1]
Walrus operator := to the rescue:
>>> x0 = 0
>>> def f(x): return x*2 + 1
...
>>> [x0:=f(x0) for _ in range(10)]
[1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]
>>> x0
1023 # x0 was modified
Solution 2:[2]
In addition to walrus, more_itertools has a function iterate that does this repeated application:
import more_itertools as mo
mo.take(10, mo.iterate(f, x0))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ForceBru |
| Solution 2 | psarka |
