How to put a list in a template sensor?

I have a template that returns a list of all devices that are unavailable. Now I want to put this list into a template sensor, that I can use in for-loops.

Currently, my template sensor looks like this:

{%- set ns = namespace(list = []) %} 
{%- for entity in state_attr("sensor.unavailable_entities","entity_id") %}
  {%- if device_id(entity) %}
    {%- set name = device_attr(device_id(entity), 'name_by_user') %}
    {%- if name and name not in ns.list|join %}
      {%- set ns.list = ns.list + [name] %}
    {%- endif %}    
  {%- endif %}
{%- endfor %}
{{- ns.list }}

When I put this into the template editor, it returns a list, but the template sensor returns a string. What can I do?

States are always strings. Only attributes may have other types. So you could use an attribute in your template sensor.