Add item(s) to yaml array only if defined (ansible)
Create the list in Jinja2 and convert it, e.g.
- hosts: localhost
  gather_facts: true
  tasks:
    - set_fact:
         ssh_listen_to: &quot;{{ _ssh_listen_to|from_yaml }}&quot;
      vars:
        _ssh_listen_to: |
          {% if ansible_default_ipv4.address is defined %}
          - {{ ansible_default_ipv4.address }}
          {% endif %}
          {% if ansible_default_ipv6.address is defined %}
          - {{ ansible_default_ipv6.address }}
          {% endif %}
    - debug:
        var: ssh_listen_to|type_debug
    - debug:
        var: ssh_listen_to

gives
TASK [debug] ********************************************************************
ok: [localhost] =&gt; 
  ssh_listen_to|type_debug: list

TASK [debug] ********************************************************************
ok: [localhost] =&gt; 
  ssh_listen_to:
  - 10.1.0.27


If you put the name of the variables into the list, e.g.
    vars_addr:
      - default_ipv4
      - default_ipv6

the task below gives the same result
    - set_fact:
         ssh_listen_to: &quot;{{ vars_addr|
                            map('extract', ansible_facts, 'address')|
                            select('defined')|
                            list  }}&quot;