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

PythonList Comprehension

Python Problem Overview


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']

Python Solutions


Solution 1 - Python

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']

Solution 2 - Python

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

Thanks @abarnert

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCoddyView Question on Stackoverflow
Solution 1 - PythonalvasView Answer on Stackoverflow
Solution 2 - PythonCT ZhuView Answer on Stackoverflow