Compare two lists in Python and return matches


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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap