Reject Filter Not Working

I am trying to randomly select lights from a group without repeating previously selected. After the first light is selected, it is added to a group named prev_on which is the group for the reject list.

When the following is run in develop tools / template, the light that is in prev_on is still included with result.

| map(attribute='entity_id')
| reject('in', expand('group.prev_on')
| map(attribute='entity_id'))
| join(', ')}}

The desired result list should be all lights in group.vacation_lights_group except those listed included in group.prev_on.

I am new to HA and this is the first one I just can’t figure out. Any help would be greatly appreciated.

The template looks fine.

If you are using it in a Template Sensor, it’s evaluated only when either group’s state changes, not when either group’s membership changes.
Let’s say both groups are off. Then the vacation group changes to on. The state-change causes the template to be evaluated. Then one of the lights in the vacation group turns off. As long as at least one other light in the group remains on, the group’s state remains on and so, without a state-change, the template is not evaluated. It doesn’t matter if the “prev_on” group increases its membership at this point. As long as neither group changed state, the template is not updated.

That’s my best guess; I haven’t tested your template on my system to confirm its behavior.


On second thought, I have decided that my initial hypothesis is BS.

The expand() function should be exposing all of the group’s membership (i.e. listeners are created for all members) and not just the group itself.

Something else is responsible for the issue and it may be more fundamental, possibly that changes to a group’s membership are not immediately detected by the template and may require a Reload Groups and/or Reload Template Entities first. Experimentation is required to gain a better understanding of what is happening here.

Taras thank you for the reply. I am trying to remove the lights in prev_on from vacation_lights group, in turn that will be piped to random() so I wasn’t anticipating the group state to matter. There is a separate trigger.

I finally got this to work. Thank you for the encouragement to experiment. I was missing | list at 2 different places.

| map(attribute='entity_id')
| list
| reject('in', expand('group.prev_on')
| map(attribute='entity_id')
| list)
| list}}

This turns out to be a simple way to eliminate devices that you don’t want in your main group.