You can compare two lists in Python and get the matches using the below two steps,
Step 1: Convert the two lists as sets using the set() function.
Step 2: Now make use of the & operator to find the intersection of the sets giving the common elements among the two lists.
Example 1:
'''
Program to find common numbers by
comparing two lists in Python
Author: Code2care.org
Version v1.0
Date: 11 July 2023
'''
numbers_list_1 = [9, 3, 5, 7, 1, 8, 2]
numbers_list_2 = [2, 4, 6, 8, 10, 7, 9]
# Finding matches
matches = set(numbers_list_1) & set(numbers_list_2)
print("List 1:", numbers_list_1)
print("List 2:", numbers_list_2)
print("Matches:", list(matches))
Output:
List 1: [9, 3, 5, 7, 1, 8, 2]
List 2: [2, 4, 6, 8, 10, 7, 9]
Matches: [8, 9, 2, 7]
Example 2:
cities1 = ['Berlin', 'Cairo', 'Moscow', 'Sydney', 'Madrid', 'Beijing', 'Rome', 'Seoul']
cities2 = ['Rome', 'Sydney', 'Berlin', 'Madrid', 'Cairo', 'Seoul', 'Beijing', 'Oslo']
matches = set(cities1) & set(cities2)
print("Common Cities:", list(matches))
Output:
Common Cities: ['Rome', 'Madrid', 'Beijing', 'Berlin', 'Seoul', 'Sydney', 'Cairo']
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!