List.Generate
ListGenerates a list of values using an initial value, a condition, a next function, and an optional selector.
Syntax
List.Generate(initial as function, condition as function, next as function, optional selector as nullable function) as listParameters
| Name | Type | Required | Description |
|---|---|---|---|
initial | function | Yes | A function that returns the initial state value. |
condition | function | Yes | A function that returns true to continue generating, false to stop. |
next | function | Yes | A function that produces the next state value from the current state. |
selector | function | No | An optional function that transforms each state value into the output value. |
Return Value
list — A list of generated values.
Remarks
List.Generate creates a list by repeatedly applying a "next" function to a state value, continuing while a condition is true. It is M's equivalent of a while loop.
Common use cases include generating date sequences, paginating API calls, and building custom number ranges.
Examples
Example 1: Generate a date range
let
StartDate = List.Min(Table.Column(Sales, "OrderDate")),
Dates = List.Generate(
() => StartDate,
each _ <= Date.AddDays(StartDate, 4),
each Date.AddDays(_, 1)
)
in
#table({"Date"}, List.Transform(Dates, each {_}))Result
Date | |
|---|---|
| 1 | 1/15/2024 |
| 2 | 1/16/2024 |
| 3 | 1/17/2024 |
| 4 | 1/18/2024 |
| 5 | 1/19/2024 |
Compatibility
✓ Power BI Desktop✓ Power BI Service✓ Excel Desktop✓ Excel Online✓ Dataflows✓ Fabric Notebooks