Template Sensor with for loop

Hi everybody,
I try to define a template Sensor with a for Loop.
Background: I want to calc when is the best time to charge my car. For this I want to look, at which time the electricity is cheapest.

First I calculate how long I want to charge (ladezeit)
After this I list the Prices. ( Preise_today )
Then I sort them (Preise_today_sort)
And I reduce them for the needed charge time (Preise_today_sort_stunden)

Now I want find the associated hour. (Preise_today have 24 values, every index is the time)

now there ist my problem, the idx is always empty, where ist the problem with my for loop? thank you for your help!

{% set ladezeit = (states('input_number.ladesteuerung_ladeziel_kwh') |float /10) |round %}

    {% set Preise_today = states.sensor.tibber_prices.attributes.today 
    | selectattr('total')
    | map(attribute='total')
    | list() %}
    {% set Preise_today_sort= (Preise_today |sort) %}
    {% set Preise_today_sort_stunden = Preise_today_sort[:ladezeit]  |list %}
    {% set idx = [] %}
    
    {% for i in range(ladezeit) %}
      {% set idx = idx + [Preise_today.index(Preise_today_sort_stunden[i])] %}
    {% endfor %}

Within a for loop you need to use namespace…

Can you try this

{% set ladezeit = (states('input_number.ladesteuerung_ladeziel_kwh') |float /10) |round %}

    {% set Preise_today = states.sensor.tibber_prices.attributes.today 
    | selectattr('total')
    | map(attribute='total')
    | list() %}
    {% set Preise_today_sort= (Preise_today |sort) %}
    {% set Preise_today_sort_stunden = Preise_today_sort[:ladezeit]  |list %}
    {% set ns = namespace(idx=[]) %}
    {% for i in range(ladezeit) %}
      {% set ns.idx = ns.idx + [Preise_today.index(Preise_today_sort_stunden[i])] %}
    {% endfor %}
     {{ ns.idx }}

well done! thank you for your help!