I want to turn the following for
loop:
JavaScript
x
7
1
n = 10
2
x0 = 0
3
values = [x0]
4
for i in range(n):
5
x0 = f(x0)
6
values.append(x0)
7
into a one liner. I figured I could do something like this:
JavaScript
1
2
1
values = [f(x0) for i in range(n)]
2
but I need to update the value of x0
in each instance of the loop. Any ideas?
Advertisement
Answer
Walrus operator :=
to the rescue:
JavaScript
1
8
1
>>> x0 = 0
2
>>> def f(x): return x*2 + 1
3
4
>>> [x0:=f(x0) for _ in range(10)]
5
[1, 3, 7, 15, 31, 63, 127, 255, 511, 1023]
6
>>> x0
7
1023 # x0 was modified
8