Home > Blockchain >  List iteration with substitution into one-liner
List iteration with substitution into one-liner

Time:05-06

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?

CodePudding user response:

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

CodePudding user response:

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))
  • Related