List.Accumulate Function in Power Query M

Sumit Bansal
Written by

Sumit Bansal is the founder of TrumpExcel.com and a 13-time Microsoft Excel MVP. He started this site in 2013 to share his passion for Excel through easy tutorials, tips, and training videos, helping you master Excel, boost productivity, and maybe even enjoy spreadsheets!

The List.Accumulate function in Power Query goes through a list one item at a time and carries a running result from one step to the next. Each step can use whatever the previous step produced.

That makes it the tool for jobs where each step builds on the last one, like running several replacements on the same text, adding a series of columns to a table, or keeping a running balance.

In this article, I’ll show you how it works with practical examples, starting with a simple sum and moving on to text clean-up, running totals, and streaks.

Follow along with the example file

List.Accumulate Function Examples.xlsx

Download

List.Accumulate Function Syntax

List.Accumulate(list as list, seed as any, accumulator as function) as any
  • list – the list of items you want to go through, one at a time.
  • seed – the starting value of the result. It can be any type: a number, text, a list, a table, or a record.
  • accumulator – a function that takes two inputs, the result so far (usually called state) and the current item (usually called current), and returns the new result.

What it returns: The final result after the accumulator has run for every item in the list. It has whatever type your seed and accumulator produce.

The accumulator is written as a small function, such as (state,current)=>state+current. The names in brackets are the two inputs, and the part after => is what the function returns.

The List.Accumulate function is part of the core Power Query M library, so it works wherever Power Query does, including Excel 365, 2024, 2021, 2019, 2016, and Power BI.

When to Use the List.Accumulate Function

Use this function when you need to:

  • Run a list of find-and-replace pairs on the same text, one after the other
  • Remove a list of words or labels from text values
  • Add several similar columns to a table in one step
  • Build a running total from a column of numbers
  • Calculate something that depends on the result of the previous step, like an account balance or a streak

Example 1: Add Up a List of Numbers

Let’s start with a simple example to see how the state and the current item move through the list.

In Excel, go to Data > Get Data > From Other Sources > Blank Query. In the Power Query Editor that opens, type this formula in the formula bar:

= List.Accumulate({120,85,240,60},0,(state,current)=>state+current)

Result: 505

List.Accumulate adds up 120, 85, 240 and 60 and returns 505

Here, the seed is 0, so the state starts at 0. For the first item, the accumulator adds 0 and 120, and the state becomes 120.

For the next item, it adds 120 and 85 to get 205. Then 205 plus 240 gives 445, and 445 plus 60 gives 505.

Since there are no more items, List.Accumulate returns the final state, 505.

For a plain sum like this, the List.Sum function is simpler, and List.Sum({120,85,240,60}) gives the same 505. The rest of the examples are jobs that List.Sum can’t do.

Also, if you only want to change each item on its own, like adding 10% to every number, use the List.Transform function instead. List.Accumulate is for when each step needs the result of the step before it.

In the example file, Examples 1 and 2 have no sheet because they don’t use any data. You can open them from Data > Queries & Connections.

Example 2: Calculate a Savings Balance with Monthly Interest

Here’s an example where the seed is not 0. Suppose a savings account starts with $1,000, you deposit a different amount each month, and the account earns 1% interest every month on the balance after the deposit.

Create a new blank query, open the Advanced Editor (Home > Advanced Editor), and use this code:

let
Deposits = {500,300,0,450,200,600},
Balance = List.Accumulate(Deposits,1000,(state,current)=>(state+current)*1.01),
Result = Number.Round(Balance,2)
in
Result

Result: 3181.24

Savings balance after six monthly deposits with 1% monthly interest: 3181.24

Here, the seed is 1000, which is the opening balance. In the first month, the accumulator adds the $500 deposit and then adds 1% interest, so the balance becomes (1000+500)*1.01, which is 1515.

The second month starts from 1515, adds the $300 deposit, and adds 1% interest again. This goes on for all six months, and the Number.Round function rounds the final balance to two decimals.

List.Accumulate is a good fit here because each month’s interest depends on the balance from the month before. You can’t work out a month without knowing the result of the previous one.

Example 3: Remove a List of Words from Text

Now let’s use List.Accumulate on text. Below is a vendor list where some company names end with Inc., LLC, or Ltd, and I want a Clean Name column with those endings removed.

Vendors table with company names ending in Inc., LLC or Ltd

The data is an Excel Table named Vendors. In the code below, the Source line uses the Excel.CurrentWorkbook function to pull that table from the current workbook by its name, so you don’t have to load it into Power Query first.

If you try this on your own data, format it as a table (Ctrl + T) and put your table’s name in place of “Vendors”. Now create a new blank query, open the Advanced Editor, and use this code:

let
Source = Excel.CurrentWorkbook(){[Name="Vendors"]}[Content],
#"Added Clean Name" = Table.AddColumn(Source,"Clean Name",each Text.Trim(List.Accumulate({"Inc.","LLC","Ltd"},[Company],(state,current)=>Text.Replace(state,current,""))),type text)
in
#"Added Clean Name"

Result: A new Clean Name column with the company names without Inc., LLC, or Ltd (Cedar Ridge Builders, Bluewater Analytics, Summit Office Supply, Pinecrest Foods, Redfield Logistics, and Oakmont Design)

A new Clean Name column with Inc., LLC and Ltd removed from each company name

Here, the list is the three words to remove, and the seed is the company name in the current row. So the state starts as the full name, such as “Bluewater Analytics Inc.”.

For each word, the Text.Replace function replaces it with nothing (“”). After all three words, the state is “Bluewater Analytics ” with a space at the end, and the Text.Trim function removes that space.

Redfield Logistics has none of the three words, so every replacement leaves it unchanged. To remove more words, just add them to the list inside the curly brackets.

Text.Replace only removes an exact match, including capital letters and periods. So if your data also has “Inc” without the period or “LTD” in capitals, add those versions to the list too.

Important: Text.Replace removes the text wherever it appears, even inside a longer word. If you add a short word like “Co” to the list, it also removes the “Co” from a name like “Coastal Foods”.

Example 4: Replace Multiple Values Using a Lookup Table

This next one is one of the most useful things you can do with List.Accumulate. Below is a staff list (a table called Staff) with shortened job titles, and I want a Full Title column with the abbreviations spelled out.

Staff table with abbreviated job titles such as Sr. Accountant and Asst. Mgr

The abbreviations and their full forms are in a separate table called Abbreviations, on the Example 4 Lookup sheet. It has a Find column (Sr., Jr., Asst., and Mgr) and a Replace column (Senior, Junior, Assistant, and Manager).

Create a new blank query, open the Advanced Editor, and use this code:

let
Source = Excel.CurrentWorkbook(){[Name="Staff"]}[Content],
Replacements = Table.ToRecords(Excel.CurrentWorkbook(){[Name="Abbreviations"]}[Content]),
#"Added Full Title" = Table.AddColumn(Source,"Full Title",each List.Accumulate(Replacements,[Job Title],(state,current)=>Text.Replace(state,current[Find],current[Replace])),type text)
in
#"Added Full Title"

Result: A new Full Title column (Senior Accountant, Assistant Manager, Junior Analyst, Sales Manager, Senior Payroll Manager, and Assistant Buyer)

A new Full Title column with the abbreviations spelled out from the lookup table

Here, the Table.ToRecords function turns each row of the Abbreviations table into a record, such as [Find=”Sr.”, Replace=”Senior”]. That gives List.Accumulate a list of four replacement pairs to go through.

For each row of the staff list, the seed is the Job Title. Each step reads the Find and Replace values from the current pair and runs the Text.Replace function, so “Sr. Payroll Mgr” becomes “Senior Payroll Mgr” and then “Senior Payroll Manager”.

The big benefit is that the replacements live in the workbook. To fix a new abbreviation, add a row to the Abbreviations table and refresh the query, without touching the M code.

The replacements run from the top row of the lookup table to the bottom, and each one works on the text the earlier rows produced. So the order of the rows can change the result.

For example, if one row turns “VP” into “Vice President” and a later row turns “Pres” into “President”, the later row would change “Vice President” to “Vice Presidentident”.

To avoid this, put the “Pres” row above the “VP” row, so no later row can match text that an earlier row added.

The Find text also has to match exactly, punctuation included. A title written as “Mgr.” would become “Manager.” with the period left over, because the “Mgr” row replaces just the letters.

If your data has both versions, add a separate “Mgr.” row above the “Mgr” row. That way “Mgr.” is replaced in full before the “Mgr” row runs.

Follow along with the example file

List.Accumulate Function Examples.xlsx

Download

Example 5: Add Several Columns in One Step

The seed doesn’t have to be a number or text. It can be a whole table, and each step can return the table with one more change.

Below is a price list of office furniture (a table called PriceList), and I want to add three columns that show each price with a 10%, 15%, and 20% discount.

Price list of office furniture with a Product and a Price column

Create a new blank query, open the Advanced Editor, and use this code:

let
Source = Excel.CurrentWorkbook(){[Name="PriceList"]}[Content],
Discounts = {10,15,20},
#"Added Discount Columns" = List.Accumulate(Discounts,Source,(state,current)=>Table.AddColumn(state,Text.From(current)&"% Off",each [Price]*(100-current)/100,type number))
in
#"Added Discount Columns"

Result: Three new columns, 10% Off, 15% Off, and 20% Off (for the Desk Lamp, that’s 36, 34, and 32)

Three new columns with each price at 10%, 15% and 20% off, added in one step

Here, the seed is the Source table. For the first discount, 10, the Table.AddColumn function adds a column named “10% Off” with each price times 90/100, and that new table becomes the state.

The next step adds the “15% Off” column to that table, and the last step adds “20% Off”. So you end up with all three columns from a single step in the Applied Steps pane.

To add a 25% column later, just add 25 to the Discounts list. The column name and the calculation both come from the number, so nothing else in the code needs to change.

For just three columns, adding three custom columns one by one works fine too. This approach pays off when the list is long or changes often.

Example 6: Create a Running Total Column

Here’s a problem that comes up all the time with sales data. Below is a table of monthly sales called MonthlySales, and I want a Running Total column that shows the total sales so far for each month.

Monthly sales table from Jan to Jun

Create a new blank query, open the Advanced Editor, and use this code:

let
Source = Excel.CurrentWorkbook(){[Name="MonthlySales"]}[Content],
RunningTotals = List.Accumulate(Source[Sales],{},(state,current)=>state&{List.Last(state,0)+current}),
#"Added Running Total" = Table.FromColumns(Table.ToColumns(Source)&{RunningTotals},Table.ColumnNames(Source)&{"Running Total"})
in
#"Added Running Total"

Result: A new Running Total column (4200, 8050, 13150, 17825, 23145, and 28125)

A new Running Total column: 4200, 8050, 13150, 17825, 23145, 28125

Here, Source[Sales] is the list of the six sales numbers, and the seed {} is an empty list. So this time the state is a list that grows by one number at every step.

At each step, the List.Last function gets the last running total in the state, and the accumulator adds the current month’s sales to it. The &{...} part adds that new total to the end of the list.

For the first month the state is still empty, so List.Last returns the default value 0 that we gave it as its second argument. That’s why January’s running total is 0+4200, which is 4200.

The last step puts the table back together. The Table.ToColumns function splits the Source table into its columns, the RunningTotals list is added as one more column, and the Table.FromColumns function rebuilds the table with the column names plus “Running Total”.

Another common way to do this is to add an Index column, and then for each row, sum the Sales values from the first row down to that row. List.Accumulate doesn’t need the Index column, because it builds all the running totals in one go.

The List.Generate function can also build a running total. It’s the better choice when you want to stop at a condition instead of going through the whole list.

Example 7: Find the Longest Streak

This last one is hard to do any other way in Power Query.

Below are the daily orders of a small online store for 14 days (a table called DailyOrders), and I want to find the longest run of days in a row with at least 50 orders.

Daily orders for 14 days

To do this, each step needs to remember two things: the length of the streak it’s currently in, and the longest streak it has seen so far. A record can hold both, so the seed here is a record.

Create a new blank query, open the Advanced Editor, and use this code:

let
Source = Excel.CurrentWorkbook(){[Name="DailyOrders"]}[Content],
Streak = List.Accumulate(Source[Orders],[Current=0,Longest=0],(state,current)=>if current>=50 then [Current=state[Current]+1,Longest=List.Max({state[Longest],state[Current]+1})] else [Current=0,Longest=state[Longest]]),
Result = Streak[Longest]
in
Result

Result: 4

The longest run of days with 50 or more orders is 4

Here, the seed [Current=0,Longest=0] starts both counts at 0. Note that current (the day’s orders) and the Current field in the record are different things, because names in M are case-sensitive.

When a day has 50 or more orders, the accumulator adds 1 to Current. The List.Max function then keeps Longest at whichever is bigger, the old Longest or the new Current.

When a day is below 50, Current goes back to 0, and Longest stays as it was.

Days 4 to 7 all have 50 or more orders, which is the longest run in the data. So the final record has Longest = 4, and the last step Streak[Longest] pulls that number out of the record.

List.Accumulate reads the days in the order they appear in the table, so make sure the data is sorted by day first. Also, the result is only the length of the streak, not which days it covers.

Other Excel Articles You May Also Like:

  • Text.TrimEnd
  • List.Combine – Use List.Combine in Power Query M to join lists into one.
  • List.Select – Use List.Select in Power Query M to keep only the list items that meet a condition.

All Power Query Functions

Sumit Bansal

Sumit Bansal

13x Microsoft Excel MVP

Hey! I'm Sumit Bansal, founder of trumpexcel.com and a Microsoft Excel MVP. I started this site in 2013 because I genuinely love Microsoft Excel (yes, really!) and wanted to share that passion through easy Excel tutorials, tips, and Excel training videos. My goal is straightforward: help you master Excel skills so you can work smarter, boost productivity, and maybe even enjoy spreadsheets along the way!

Get the FREE 51 Excel Tips Ebook

Enter your details and the free PDF is on its way to your inbox.

Hmm, that didn't go through. Please check your email and try again.

No spam. You'll also get my weekly Excel newsletter. Unsubscribe anytime.

Check your inbox!

The ebook is on its way to your email. It usually lands within a couple of minutes.