Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Building Running Totals With accumulate()

00:00 In this lesson, you’ll use accumulate() to build running totals, running minimums, and more, and you’ll see why the order of a function’s arguments matters.

00:10 accumulate() takes an iterable and a function with two arguments. Here’s the input one, two, three, four, five. The first output is always the first input, one.

00:21 Then accumulate() adds the previous result to the next input. One plus two gives you three. Three plus three gives you six. Six plus four gives you ten. And ten plus five gives you fifteen.

00:33 Each output feeds into the next step. Here’s that example in the REPL. The operator module gives you addition as a function. Pass operator.add, and you get the running total you just saw.

00:46 Addition is the default, so you can leave it out.

00:50 Since Python 3.8, you can pass an initial value. It becomes the first output, so there’s one more value than in the input. You can pass any function with two arguments.

01:01 With the built-in min(), you get a running minimum.

01:05 The first argument of your function is always the result so far, and the second is the next input. Subtract the next value from the result, and the total keeps shrinking.

01:17 Swap them around, and you get a completely different sequence. This time, each value is the new number minus the running result. In this lesson, you built running totals and running minimums with accumulate().

01:30 In the tutorial, you’ll also find how accumulate() can generate any sequence defined by a recurrence relation. Now it’s time to get back to your deck of cards.

01:40 Next up, you’ll shuffle it and cut it without copying it.

Become a Member to join the conversation.