Pythonic way to create union of all values contained in multiple lists

AJ. picture AJ. · Jan 28, 2010 · Viewed 52.3k times · Source

I have a list of lists:

lists = [[1,4,3,2,4], [4,5]]

I want to flatten this list and remove all duplicates; or, in other words, apply a set union operation:

desired_result = [1, 2, 3, 4, 5]

What's the easiest way to do this?

Answer

sth picture sth · Jan 28, 2010

set.union does what you want:

>>> results_list = [[1,2,3], [1,2,4]]
>>> results_union = set().union(*results_list)
>>> print(results_union)
set([1, 2, 3, 4])

You can also do this with more than two lists.