Search code examples
pythonlistfor-loopone-liner

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

  • 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