Union of Lists in Python

Find the union of two lists (unique elements from both).

BeginnerList ProgramsExample 8 of 25
union-of-lists.py
Run in browser
1# Program to find union of two lists
2
3list1 = input("Enter first list elements: ").split()
4list2 = input("Enter second list elements: ").split()
5
6union = list(set(list1) | set(list2))
7
8print("Union:", union)

Output

Enter first list elements: 1 2 3
Enter second list elements: 3 4 5
Union: ['1', '2', '3', '4', '5']

What's going on

We use set union (|) to collect all distinct elements from both lists.