How to select a random input_select option, but not the same one that is already selected?

I am working on my Halloween automations. I have one that uses an input_select list to play a random spooky video on my projector. It works great, but it all-too-often selects the same video that was played last.

Is there a way to modify my code below so that it still selects a random option, but not the one that is currently selected?

     # x = Count of input_select options
     # i = Randomly selected option index
    - service: input_select.select_option
      entity_id: input_select.ghost_video
      data_template:
        option: >
          {%- set x = state_attr('input_select.ghost_video','options') | length | int -1 -%}
          {%- set i = (range(0, x) | random | int) -%}
          {%- set options = state_attr('input_select.ghost_video','options') -%}
          {{ options[i] }}
1 Like

Reject the current value from the options list then randomly select an item from the resulting (shorter) list.

    - service: input_select.select_option
      target:
        entity_id: input_select.ghost_video
      data:
        option: >
          {{ state_attr('input_select.ghost_video', 'options')
              | reject('eq', states('input_select.test'))
              | list | random }}
2 Likes

Thank you, @123 ! This is great! One more question. There is one more option that I want to hard code so it is never selected by this automation. The below seems to work. Does this look correct to you?

    - service: input_select.select_option
      target:
        entity_id: input_select.ghost_video
      data:
        option: >
          {{ state_attr('input_select.ghost_video', 'options')
              | reject('eq', states('input_select.ghost_video'))
              | reject('eq', 'My option value')
              | list | random }}

That should work but you can simplify it like this:

    - service: input_select.select_option
      target:
        entity_id: input_select.ghost_video
      data:
        option: >
          {{ state_attr('input_select.ghost_video', 'options')
              | reject('in', [states('input_select.ghost_video'), 'My option value'])
              | list | random }}
7 Likes