Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 355
AJ. Avatar asked Jan 28 '10 00:01

AJ.


People also ask

How do you create a union with multiple lists in Python?

In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

How do you create a union of two lists?

Use plus “+” operator to Union of two lists in Python. Union of two lists means combining two lists into one, all the elements from list A and list B, and putting them inside a single new list.

How do you create a union list in Python?

To perform the union of two lists in python, we just have to create an output list that should contain elements from both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the union of list1 and list2 will be [1,2,3,4,5,6,8,10,12] .


2 Answers

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.

like image 97
sth Avatar answered Sep 18 '22 02:09

sth


Since you seem to be using Python 2.5 (it would be nice to mention in your Q if you need an A for versions != 2.6, the current production one, by the way;-) and want a list rather than a set as the result, I recommend:

import itertools  ...  return list(set(itertools.chain(*result_list))) 

itertools is generally a great way to work with iterators (and so with many kinds of sequences or collections) and I heartily recommend you become familiar with it. itertools.chain, in particular, is documented here.

like image 30
Alex Martelli Avatar answered Sep 18 '22 02:09

Alex Martelli