Uwe.Schneider
Uwe.Schneider

Reputation: 1415

How to access the previous item calculated in a list comprehension?

when I create a list, I use the one-liner

new_list = [func(item) for item in somelist]

Is there a simple way to write the following iteration in one line?

new_list = [0]
for _ in range(N):
    new_list.append(func(new_list[-1]))

or even

new_list = [0]
for t in range(N):
    new_list.append(func(t, new_list[-1]))

i.e. each item is calculated based on the previous item with a specific initializer.

Upvotes: 0

Views: 62

Answers (2)

blhsing
blhsing

Reputation: 106553

You can use an assignment expression to store the returning value of the last call to func, but since you also want the initial value 0 to be in the list, you would have to join it separately:

new_list = [i := 0] + [i := func(i) for _ in range(N)]

or even:

new_list = [i := 0] + [i := func(t, i) for t in range(N)]

Upvotes: 2

Bharel
Bharel

Reputation: 26900

itertools.accumulate() exists exactly for that:

from itertools import accumulate

new_list = list(accumulate(range(N), func))  # == [0, func(0, 1), func(func(0, 1), 2), ...]

If you wish to dump the N, just use accumulate like so:

from itertools import accumulate

new_list = list(accumulate(range(N), lambda x, y: func(x)))  # == [0, func(0), func(fnc(0)), ...]

Upvotes: 2

Related Questions