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: 1, 2, 3, 4, 5. The first output is always the first input, 1.

00:20 Then accumulate() adds the previous result to the next input. 1 plus 2 gives you 3, 3 plus 3 gives you 6, 6 plus 4 gives you 10, and 10 plus 5 gives you 15.

00:32 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. 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.

00:58 You can pass any function with two arguments. With the built-in min(), you get a running minimum. The first argument of your function is always the result so far, and the second is the next input.

01:11 Subtract the next value from the result and the total keeps shrinking. Swap them around and you get a completely different sequence. This time, each value is the new number minus the running result.

01:26 In this lesson, you built running totals and running minimums with accumulate(). In the tutorial, you’ll also find how accumulate() can generate any sequence defined by a recurrence relation.

01:37 Now it’s time to get back to your deck of cards. Next up, you’ll shuffle it and cut it without copying it.

Become a Member to join the conversation.