Union of Lists in Python
Find the union of two lists (unique elements from both).
BeginnerList ProgramsExample 8 of 25
union-of-lists.py
1# Program to find union of two lists23list1 = input("Enter first list elements: ").split()4list2 = input("Enter second list elements: ").split()56union = list(set(list1) | set(list2))78print("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.
After this program
If the idea is still fuzzy, read Day 5: Lists and List Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 list programs, or see every topic on Python exercises.