List.Generate

List

Generates a list of values using an initial value, a condition, a next function, and an optional selector.

Examples on this page use shared sample tables. View them to understand the input data before reading the examples below.

Syntax

List.Generate(initial as function, condition as function, next as function, optional selector as nullable function) as list

Parameters

NameTypeRequiredDescription
initialfunctionYesA function that returns the initial state value.
conditionfunctionYesA function that returns true to continue generating, false to stop.
nextfunctionYesA function that produces the next state value from the current state.
selectorfunctionNoAn optional function that transforms each state value into the output value.

Return Value

listA 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
11/15/2024
21/16/2024
31/17/2024
41/18/2024
51/19/2024

Compatibility

Power BI Desktop Power BI Service Excel Desktop Excel Online Dataflows Fabric Notebooks