Iteration through a list

Bear with me, this is a complex one, but I’m hoping to change it into a “Share your projects” one.

I was trying to help a fellow user (@easwaran83) recently and the topic turned into a question like “how do I go through a list of items randomly without repeating any item”?
I don’t (yet) have a use case for this but can see it becoming of use at some stage (e.g. picking up a random item from an inventory until the inventory is finished and needs replenishing)
so this is what I started with in my mind:

  1. an input_select to store the inventory list
  2. an input_select with numbers (0 to inventory length) sorted in random order which would become the location of the next inventory item to select (similar to lookup in excel)
  3. a counter to keep track of where we are in the list of random numbers
  4. an automation to initialise the input_select list of numbers
  5. a script to pick up the next inventory item and increase the counter

Straight away I struggled with a few things:

  1. programmatically populate an input_select with numbers. For some reason I always end up with all my numbers as an array on the first row of the input_select.
    Here is an example code I’ve used. What am I doing wrong?
inventory_set_random_list:
  alias: Set inventory Pickup List
  sequence:
    - service: input_select.set_options
      data_template:
        entity_id: input_select.inventory_position
        options: >-
          {%- set mylist = '28 85 45 17 99 48 38 73 13 27 11' -%}
          {{mylist.split(" ")}}

Here is the result:

  1. shuffle the input_select list in random order. I’ve created a list of 11 unique numbers sorted in random order. If I had a list of say 500 numbers, how would I sort them in random order? Alternatively I can pull a random list via a scrape sensor, but I still need to be able to “load” it to my input_select…

Any ideas?

1 Like

keeping this for later

Hi @lolouk44, about the input_select, read here

Maybe it’s also usefull for the second part.

Thanks, I was hoping I’d have everything in a yaml / jinja script. Guess I’ll have to create a python script for this.
Will try and feedback

The problem, I believe, with trying to generate a list with a Jinja template is the template will only output one string. Even if you try to split it into multiple lines, it will still output one string (but with \n characters in it.) I think I’ve seen limited cases of this working (e.g., something like [{{ template1 }},{{ template2 }}, ... ]), but I’m not even 100% sure about that anymore. And even if this does work, you can’t “share” anything between the templates, so they act completely separately.

1 Like