Paradoxks
Paradoxks

Reputation: 1

Nested loop on a list with a function

I got stuck on that:

How can I express this situation with loops?

B1 = func(C , y[0])
B2 = func(B1 , y[1])
B3 = func(B2 , y[2]) #.... and so on.

Upvotes: 0

Views: 122

Answers (2)

Casper S
Casper S

Reputation: 118

There are a few ways to do this:

First of all, regular loop:

C = ...  # the constant
b = C
for i in y:
   b = func(b, i)

But using a reduce like this, is my preferred way of doing this:

from functools import reduce
b = reduce(func, y, C)  # the last arg being the initial item used

You could also use the walrus notation, which is only useful (IMO) when saving the intermediate states.

bs = [(b := func(b, yi)) for yi in y)]
b  # b being the end result

Upvotes: 1

chepner
chepner

Reputation: 531055

The first argument is just the return value of the previous call, starting with C:

result = C
for yval in y:
    result = func(result, yval)

As pointed out in the comments, this pattern is captured by the often overlooked reduce function. (Overlooked, in part, because it was demoted from the built-in namespace to the functools module in Python 3.)

from functools import reduce


result = reduce(func, y, C)

Upvotes: 2

Related Questions