Updated on

List.ReplaceRange is a Power Query M function that replaces a specified number of values in a list with another list, starting at a specified position. The function returns a modified list with the specified range replaced.

Compatible with: Power BI Service Power BI Desktop Excel Microsoft 365


   list as list,
   index as number,
   count as number,
   replaceWith as list,
) as list


The List.ReplaceRange function replaces a specific segment within a list with a new set of values. The function operates by removing the specified range of elements from the original list and then inserting the new values at the same starting index. It returns a new list with the specified segment replaced, maintaining the original order of the unaffected elements.


Basic Range Replacement

Suppose you have a list { 1, 1, 1, 4, 5 }. To replace a range starting from the second element (1 at index 1) with the values { 2, 3 }, the function is used as follows:

// Returns { 1, 2, 3, 4, 5 }
List.ReplaceRange( { 1, 1, 1, 4, 5 }, 1, 2, { 2, 3 } )

This shows List.ReplaceRange can selectively replace a specific segment within a list.

Text Value Replacement

When working with text values, such as replacing the first two elements of { "A", "B", "Dan", "Ace" } with { "Avi", "Ben" }, the function operates similarly:

// Returns { "Avi", "Ben", "Dan", "Ace" }
List.ReplaceRange( { "A", "B", "Dan", "Ace" }, 0, 2, { "Avi", "Ben" } )

Regardless of the data type within the list, the function can replace its contents.

Replacing More Values Than Inserted

List.ReplaceRange can also replace a larger range of values with a smaller number of new values:

// Returns { "Avi", "Ben" }
List.ReplaceRange( { "A", "B", "Dan", "Ace" }, 0, 4, { "Avi", "Ben" } )

Here, four elements are replaced by only two, showing how the operation can also remove values.

Inserting More Values Than Replaced

Conversely, the function can insert more values than it replaces:

// Returns { "Aad", "Bas", "Cas", "Gia", "Dan", "Ace" }
List.ReplaceRange( { "A", "B", "Dan", "Ace" }, 0, 2, { "Aad", "Bas", "Cas", "Gia" } )

That means List.ReplaceRange can be used to extend the list by inserting additional elements in place of a smaller number of existing ones.

Learn more about List.ReplaceRange in the following articles:

Other functions related to List.ReplaceRange are:

BI Gorilla Blog

Contribute » | Contributors: Rick de Groot
Microsoft documentation: