Thank you for your quick response. I suspect that I am doing something wrong. I am getting an error TemplateSyntaxError: expected token ‘end of statement block’, got ‘(’
You should have only replaced lights in this line {{ expand(lights) | selectattr('state','eq','on') | list | count }}. {% set lights = ... should have remained the same.