Sum in a FOR loop

Hi all, probably something really simple that I just can’t understand. But why isn’t the below yaml summing up to 5, but result is zero? Why is this not working???

{% set result = 0 %}
{% set list = [1,2,3,4,5] %}

{% for item in list %}
{% set result = result+ 1 %}
{% endfor %}

{{ result}}

Above jaml is a simplified version of what I actually want to accomplish, because this is what I need;

  • I want to sum the up_kilobytes_per_s attribute for all device_trackers within the integration tplink_deco, that are connected to a specific AP (deco_device), so I know the total kilobytes_per_s for that specific AP
{% set result = 0 %}
{% set array = integration_entities('tplink_deco') | list %} {# this will create a list of device_trackers within the custom integration 'tplink_deco'#}

{% for a in array if state_attr(a, 'icon') == 'mdi:lan-connect' and state_attr(a, 'deco_device') == 'Mid'%}
{% set result = result+ state_attr(a, 'up_kilobytes_per_s') %}
{% endfor %}

{{ result}}

That has to do with the scope of variables, i.e. in your example the inner result overrides the outer result. The below code does what you are looking for:

{% set ns = namespace(result=0) %}
{% set list = [1,2,3,4,5] %}

{% for item in list %}
{% set ns.result = ns.result + 1 %}
{% endfor %}

{{ ns.result}}
2 Likes

Not an answer to the topic question, but I think this should work with no need for a loop:

{{ states.device_tracker
   |selectattr('entity_id', 'in', integration_entities('tplink_deco'))
   |selectattr('attributes.icon', 'eq', 'mdi:lan-connect')
   |selectattr('attributes.deco_device', 'eq', 'Mid')
   |map(attribute='attributes.up_kilobytes_per_s')
   |select('number')
   |sum }}
1 Like