List comprehension in template?

I’m looking for a way to apply math to every element in a list.

I have a sensor with an attribute numbers that looks something like this (an array of numbers):
[1,2,3,4,5,6,7]

I’ve made a custom sensor, also with an attribute numbers, and I want to fill it with the same values as the other sensor except have every value offset by some number, for example 1.
If list comprehension was a thing, I would do it like this:

{% set numbers = states['sensor.example_sensor'].attributes.numbers%}

{{ [n+1 for n in numbers] }}

I’ve looked around for a way to do it but I couldn’t find anything that would do the trick.

I can do this:

{% set numbers = states['sensor.example_sensor'].attributes.numbers %}

{% for n in numbers %}
  {{n +1}}
{% endfor %}

Which would output:

2

  3

  4

  5

  6

  7

  8

But that’s just printing the numbers across multiple lines, not a proper array

Is there a way to do something similar to list comprehension in jinja? Or maybe some way I can make my example solution format the output as an array instead of printing the numbers across multiple lines?

You have to build a new list containing the incremented values.

{% set ns = namespace(x=[]) %}
{% for i in state_attr('sensor.example_sensor', 'numbers') %}
  {% set ns.x = ns.x + [i + 1] %}
{% endfor %}
{{ ns.x }}

Example

1 Like

Awesome! Thank you!

I hadn’t thought about using {% set %} inside the loop, but that works perfectly

1 Like

The following PR might be of interest to you. Its author is attempting to enhance Home Assistant’s implementation of Jinja2 by allowing for a mutable list.

1 Like