List.First

Updated on

List.First is a Power Query M function that retrieves the first item in a list or returns a default value if the list is empty. The function returns the first item or null if no default value is specified and the list is empty.

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

Syntax

List.First(
   list as list,
   optional defaultValue as any,
) as any

Description

The List.First function retrieves the first item from a list. If the list is empty, the function returns a null value by default. However, users can specify an optional second argument to provide a default return value in cases where the list is empty.

Examples

The List.First function retrieves the first item from a list. Let’s dive into its applications with some real-world examples.

Extract First Item from List

Consider a scenario where you have a list of students, arranged in the order they registered. To identify the student who came first, you can use:

// Output: "Alice"
List.First( { "Alice", "Bob", "Charlie" } )

For those familiar with item-selection for lists, the same result can be achieved by:

// Output: "Alice"
{ "Alice", "Bob", "Charlie" }{0}

If you’re working with a chronological list of dates, pinpointing the starting date is straightforward:

// Output: #date(2023, 1, 1)
List.First( { #date(2023, 1, 1), #date(2023, 1, 2), #date(2023, 1, 3) } )

Handling Empty Lists

When you apply List.First to an empty list, it naturally returns a null value:

// Output: null
List.First( {} )

This behavior mirrors the outcome when using optional field-selection on an empty list:

// Output: null
{}{0}?

Providing a Default Value

There might be instances where a null return isn’t ideal. In such cases, List.First allows you to set a default return value:

// Output: "The List is empty"
List.First( {}, "The list is empty" )

For those who prefer a more advanced approach, combining optional item selection with the coalesce operator achieves a similar outcome, although in a less intuitive manner:

// Output:"The list is empty"
{}{0}? ??"The list is empty"

In conclusion, the List.First function offers a straightforward way to access the first item in a list. It is more explicit than using item-selection and allows for a convenient way to return a default value.

Learn more about List.First in the following articles:

Other functions related to List.First are:

Contribute » | Contributors: Rick de Groot
Microsoft documentation: https://learn.microsoft.com/en-us/powerquery-m/list-first

2023-2024 © BI Gorilla. All rights are reserved. Information from Microsoft docs is property of Microsoft Corp. | Privacy Policy