Skip to article frontmatterSkip to article content
Template function

Flatten

One function for a flat belly in seconds πŸ«ƒπŸ»

The flatten function provides an easy way to flatten a list of lists into a single list.

Template function properties
FunctionFlatten a lists of lists
Function nameflatten
ReturnsA flattened list
Return typelist of items
Can be used as a filterYes
Can be used as a testNo
Spook's influenceNewly added template function
Developer toolsTry this in the template developer tools
Signature
flatten(
    value: Iterable[Any]
    levels: int | None = None,
) -> list[Any]
Function parameters
AttributeTypeRequiredDefault / Example
itemslist of itemsYes["a", ["b", ["c"]]]
levelsNone, integerNoNone

The levels parameter can be used to specify how many levels of lists should be flattened. By default, all levels are flattened.

ExamplesΒΆ

Using flatten as a functionΒΆ

1
{{ flatten([1, [2, [3]], 4, [5 , 6]]) }}

Returns:

[1, 2, 3, 4, 5, 6]

Using flatten as a filterΒΆ

1
{{ [1, [2, [3]], 4, [5 , 6]] | flatten }}

Returns:

[1, 2, 3, 4, 5, 6]

Using a levelsΒΆ

You can define how many levels of lists should be flattened. By default, if no levels are specified, all levels are flattened.

Example:

1
{{ flatten([1, [2, [3]]], levels=1) }}

Returns:

[1, 2, [3]]

Features requests, ideas, and supportΒΆ

If you have an idea on how to further enhance the Home Assistant template engine, for example, by adding a new template function; feel free to let us know in our discussion forums.

Are you stuck using this new feature? Or maybe you’ve run into a bug? Please check the Support page on where to go for help.