Power Query List.Generate Function: Guide and Examples
In this article
The List.Generate function in Power Query is used to create a list of values based on a set of rules, specifically when the next value in the list depends on the previous one. Unlike List.Numbers, which creates a simple sequence, List.Generate allows for complex logic, such as looping until a specific condition is met or calculating a running total that determines when to stop. This is essential for tasks like creating custom calendars, generating a series of dates for financial forecasting, or handling API pagination where the next page URL is provided by the current page's response.
What You'll Need
- Microsoft Excel or Power BI Desktop.
- Access to the Power Query Editor (Get Data > Launch Power Query Editor).
- A basic understanding of the M language syntax (the functional language behind Power Query).
- The Advanced Editor window (found under the View tab) to write the function manually, as
List.Generatecannot be created using the standard ribbon buttons.
Step-by-Step
- Open the Advanced Editor: In Power Query, go to the View tab and select Advanced Editor. This is necessary because
List.Generaterequires a specific functional syntax that the user interface does not provide through a menu. - Define the Initial Value: The first argument of
List.Generateis theinitialvalue. This is the starting point of your list. For example, if you are counting from 1 to 10, your initial value is1. If you are generating a record (which is common for complex lists), you might start with[Counter = 1, Value = 0]. - Set the Condition: The second argument is the
condition. This is a logical test that Power Query evaluates before generating each item. As long as this condition istrue, the function continues to add items to the list. Once it evaluates tofalse, the list stops. For a count to 10, the condition would beeach _ <= 10(where the underscore represents the current item in the list). - Define the Next Step: The third argument is the
nextfunction. This tells Power Query how to calculate the next value based on the current one. For a simple increment, you would useeach _ + 1. If you are using records, you would define the update for each field, such aseach [Counter = [Counter] + 1, Value = [Value] * 2]. - Select the Output (Optional): The fourth argument is the
selector. By default,List.Generatereturns the entire state of the iteration. If your state is a record but you only want a specific value from that record to appear in the final list, the selector extracts that specific field. For example,each [Value]would ensure the list contains only the calculated values, not the counters. - Convert the List to a Table: Once the function is executed, you will see a List object in the Power Query window. To make this data usable for reporting, go to the Transform tab and select To Table. This converts the list into a column that can be expanded, filtered, or merged with other data sources.
- Set Data Types: After converting to a table, click the data type icon in the column header to set the correct type (e.g., Whole Number, Date, or Decimal Number) to ensure calculations in your report are accurate.
Common Mistakes
One of the most frequent errors is creating an infinite loop. This happens when the condition argument is written in a way that it can never evaluate to false. For instance, if you start at 1 and increment by 1, but your condition is each _ > 0, the function will run until the system runs out of memory or the application crashes. Always ensure your condition has a clear, reachable exit point.
Another common mistake is incorrect record referencing. When using records as the state (the initial and next arguments), users often forget that the underscore _ represents the entire record. To access a field within that record in the next step, you must use square brackets, such as _[Counter]. Simply writing Counter + 1 will result in an expression error because Power Query does not know which record the field belongs to.
Users also frequently confuse List.Generate with List.Accumulate. While both involve iterative logic, List.Accumulate returns a single final value (the result of the accumulation), whereas List.Generate returns a list of every intermediate value produced during the process. If you need a history of the steps, use Generate; if you only need the final total, use Accumulate.
Tips
To handle complex API calls, use a Record as your state. Instead of just tracking a page number, you can track the page number, the total number of records found, and the URL for the next page. This allows the condition to check if the "NextPageURL" field is null, providing a dynamic way to stop the loop regardless of how many pages exist.
When working with dates, combine List.Generate with Date.AddDays. This is far more flexible than List.Dates if you need to skip weekends or holidays. You can write a next function that checks if the resulting date is a Saturday or Sunday and adds an additional day if necessary, effectively creating a business-day-only list.
For performance optimization, avoid performing heavy transformations inside the next function. The next function runs for every single row generated. If you are performing a complex merge or a web call, try to keep the logic as lean as possible to prevent the query from slowing down during the refresh process.
Troubleshooting
If your query is hanging or taking forever to load, you likely have an infinite loop. The first step is to stop the refresh and check your condition argument. Ensure that the value being tested is actually changing in the next step. If the value remains static, the condition will never change from true to false.
If you receive a "Expression.Error: The field 'X' of the record wasn't found", check your record field names. M is case-sensitive. If you defined your initial record as [Counter = 1] but tried to reference it as _[counter] (lowercase 'c') in the next step, the function will fail. Verify that the casing matches exactly across the initial, condition, and next arguments.
If the list is empty, your initial value likely failed the condition test immediately. Power Query evaluates the condition for the very first item before adding it to the list. If your initial value is 11 and your condition is each _ <= 10, the list will be empty because the starting point already violates the rule.
Frequently Asked Questions
Can List.Generate replace a For loop?
Yes, List.Generate is the functional equivalent of a while or for loop in traditional programming. It allows you to iterate through a process until a specific state is reached.
Is List.Generate case-sensitive?
Yes, the M language is entirely case-sensitive. This applies to the function name itself, the field names within records, and any text comparisons used within the condition or next arguments.
How do I handle API pagination with this function?
Set the initial value to the first API call result. Set the condition to check if the "next link" field in the response is not null. In the next step, make the API call using the URL found in the current result's "next link" field.
Can I generate a list of multiple columns?
Technically, List.Generate creates a list. To get multiple columns, you must generate a list of records. Each record can contain multiple fields. Once the list is generated, you can convert it to a table and expand the records into separate columns.
Does List.Generate support asynchronous calls?
No, Power Query executes these steps sequentially. Each iteration must complete and return a value before the next function can be called for the subsequent item.
What is the difference between the underscore (_) and the selector?
The underscore represents the current state of the iteration used in the condition and next steps. The selector is a final filter that decides which part of that state is actually stored in the resulting list.