'Ansible: Removing empty values from a list and assigning it to a new list

I have a list generated in ansible using values gathered by a task. In that list, there are empty strings as some of the keys don't have values assigned to them. So, what I am trying to achieve is to assign that list to a new list but without those empty values.

list1: [
   "a",
   "b",
   "",
   "7",
   ""
]

I have tried the following and it doesn't seem to work:

set_fact:
  list2: "{{ list1 1 | rejectattr('') |list }}"

Is anyone able to point me what I am doing wrong and provide a solution to my issue?

Ansible version: 2.9.1



Solution 1:[1]

Q: Remove empty values from list1 ["a", "b", "", "7", ""]

A: Simply use the select filter. Quoting:

"If no test is specified, each object will be evaluated as a boolean."

    - set_fact:
        list2: "{{ list1|select() }}"
      vars:
        list1: ["a", "b", "", "7", ""]

gives

    list2: [a, b, '7']

Q: If an element is 0 or False ?

A: Both 0 and False evaluate to boolean False. The filter select will remove them too

    - set_fact:
        list2: "{{ list1|select() }}"
      vars:
        list1: ["a", "b", 0, "7", False, ""]

gives the same result

    list2: [a, b, '7']

If you want to reject empty strings only then use the match filter

    - set_fact:
        list2: "{{ list1|reject('match', '^$') }}"
      vars:
        list1: ["a", "b", 0, "7", False, ""]

gives

    list2: [a, b, 0, '7', false]

Solution 2:[2]

Please try as below

  vars:
   list1: [ "a", "b", "", "7", "" ]
   list2:  []

  tasks:
  - name: test
    set_fact:
     list2: "{{list2  + [item]}}"
    when: item != ""
    with_items:
     - "{{list1}}"

Output

ok: [localhost] => {
    "msg": [
        "a",
        "b",
        "7"
    ]
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Smily