states.light.e27 is a single light, its not a list. You’re asking it to treat it like a list. You have to expand the group of lights inside it first, try this:
{{ state_attr('light.e27', 'entity_id')
| expand
| selectattr('state', 'eq', 'on')
| list
| count
}} # >> Only returns the count of groups though not entities
When you expand a nested Group, it will return all entities from its sub-Groups. Based on your observation, it appears that it doesn’t work the same way for a Light Group; it only returns its direct child-groups and no further.
Ah. light.e27 is a light group containing other light groups. That’s going to be a problem because of what 123 said - you can’t expand a light group like a group, you have to expand its entity_id attribute.
I’m not really sure if there’s a good, generic solution to this problem. You would need to be able to recurse or use a while loop in order to loop through children expanding groups until you got to all the leaf nodes and a Jinja template can’t do either of those things. There is a kind of crappy solution though, you can just loop over an arbitrarily high range and pretend its a while loop using the conditional loop option. So something like this:
{% set ns = namespace(queue=["light.e27"], lights=[]) %}
{% for a in range(1, 100) if ns.queue | count > 0 %}
{% set light = (ns.queue[-1] | expand)[0] %}
{% set ns.queue = ns.queue[0:-1] %}
{% if light.attributes.entity_id is defined %}
{% set ns.queue = ns.queue + light.attributes.entity_id %}
{% else %}
{% set ns.lights = ns.lights + [light] %}
{% endif %}
{% endfor %}
{{ ns.lights | selectattr('state', 'eq', 'on') | list | count }}
EDIT: In case your wondering as I was, Jinja does not have a break like python does. Which is annoying as this solution would be significantly less crappy with that. Without recursion, while loops or break I think this is kind of the best that can be done here.