0

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Uwe.Schneider
  • 1,112
  • 1
  • 15
  • 28
  • Does this answer your question? [Python list comprehension - access last created element?](https://stackoverflow.com/questions/794774/python-list-comprehension-access-last-created-element) – Tomerikoo Jan 18 '23 at 10:07

2 Answers2

2

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)]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
blhsing
  • 91,368
  • 6
  • 71
  • 106
2

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)), ...]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Bharel
  • 23,672
  • 5
  • 40
  • 80