Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{'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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading