Search code examples
pythonlist-comprehension

Python - Flatten sets and tuples into one list of sets


Hoping someone can help me with this. I have a list of sets and tuples, and I want to flatten it to one list of sets.

What I have:

 [({'item1', 'item2'}, 'item_a'),
 ({'item1', 'item2'}, 'item_b'),
 ({'item2', 'item3'}, 'item_a'),
 ({'item2', 'item3'}, 'item_b')]

Desired output:

[{'item1', 'item2', 'item_a'},
 {'item1', 'item2', 'item_b'},
 {'item2', 'item3', 'item_a'},
 {'item2', 'item3', 'item_b'}]

I have tried these functions, but it doesn't work:

list_flat = [item for sublist in list for item in sublist]

and

flat_list = []
for sublist in t:
    for item in sublist:
        flat_list.append(item)

Solution

  • Use iterable unpacking:

    >>> l1 = [
    ...  ({'item1', 'item2'}, 'item_a'),
    ...  ({'item1', 'item2'}, 'item_b'),
    ...  ({'item2', 'item3'}, 'item_a'),
    ...  ({'item2', 'item3'}, 'item_b')
    ... ]
    >>> l2 = [{b, *a} for a, b in l]
    >>> l2
    [{'item2', 'item_a', 'item1'}, {'item2', 'item_b', 'item1'}, {'item2', 'item_a', 'item3'}, {'item2', 'item_b', 'item3'}]
    

    (the nested sets are unordered)

    The list comprehension uses sequence unpacking twice:

    1. to unpack the (set, string) tuples in the original list.
    2. to unpack the set to create a new set