ERROR UndefinedError: No last item, sequence was empty

Hi All,

does anyone know why I get this error, i have stolen the code and was hoping to use it myself but i get “UndefinedError: No last item, sequence was empty.” the code sort of works sometimes i can see the updates, other time i get the above error

- platform: template
    sensors:
      room_audio:
        friendly_name: "Room Audio"
        value_template: >-
         {% set sensor = 'main' %}
          {% if is_state('input_boolean.audible_notifications', 'on') %}
            {% set sensor = expand('group.occupancy') | selectattr('state', 'eq', 'on') | sort(attribute='last_changed') | last %}
            
          {% else %}

            {% set sensor = expand('group.occupancy_night') | sort(attribute='last_changed') | last %}

          {% endif %}

          {% if sensor.name in ['Main Bedroom motion sensor Motion'] or sensor == 'main_bedroom_motion_sensor_motion' %}
            master_bedroom
          {% elif sensor.name in ['Living Room Motion',] or sensor == 'living_room_motion' %}
            living_room
          {% elif sensor.name in ['Natalie Motion Sensor' ] %}
            natalies_room
             
{% else %}
            master 
          {% endif %}