Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the union of two lists using list comprehension? [duplicate]

Consider the following lists:

a = ['Orange and Banana', 'Orange Banana'] b = ['Grapes', 'Orange Banana'] 

How to get the following result:

c = ['Orange and Banana', 'Orange Banana', 'Grapes'] 
like image 375
Coddy Avatar asked Jan 02 '14 23:01

Coddy


People also ask

How do you create a union of two lists 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] .

What is a union of two lists?

Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists.


2 Answers

If you have more than 2 list, you should use:

>>> a = ['Orange and Banana', 'Orange Banana'] >>> b = ['Grapes', 'Orange Banana'] >>> c = ['Foobanana', 'Orange and Banana'] >>> list(set().union(a,b,c)) ['Orange and Banana', 'Foobanana', 'Orange Banana', 'Grapes'] 
like image 96
alvas Avatar answered Sep 17 '22 05:09

alvas


>>> list(set(a).union(b)) ['Orange and Banana', 'Orange Banana', 'Grapes'] 

Thanks @abarnert

like image 27
CT Zhu Avatar answered Sep 21 '22 05:09

CT Zhu