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!
More Posts related to Python,
- Python: Convert Date to DateTime
- How to sort a List using Lambda in Python
- Python matplotlib segmentation fault: 11 macOS Big Sur
- What is Terminal Velocity and its Formula? How to calculate it programmatically?
- How to install Python 3.11 on Mac
- How to flatten a nested list in Python
- Python: Pandas Merge DataFrames on Index Example
- How to Run all Cells at Once Jupyter Notebook
- Python - Convert float to String
- How to add borders to tkinter label text
- How to Exit a Loop in Python Code
- [Python] Fix: ValueError: All arrays must be of the same length
- Sorting an array using Bubble Sort in Python Programming
- How to Unzip a file using Python
- Python: Merge DataFrames Pandas Outer Join Example
- Change label (text) color in tkinter
- Convert Float to String in Python
- Fix: fatal error: No such file or directory compilation terminated
- Python: Access index/counter of a for loop iteration
- Import Other Python Files Examples
- How to install Anaconda on Mac (M1/M2 Mac)
- Python Regular Expression to Find All Matches in List
- How to Read a binary File with Python
- How to disable warnings while Python file execution
- Know current Python Version
More Posts:
- cURL DELETE Request with Examples - cURL
- Pandas: Reading .xlsx or .xls Excel Files - Python
- SharePoint formula - Calculated columns cannot contain volatile functions like Today and Me - SharePoint
- Spring Boot: @RequestBody not applicable to method - Java
- Display Era details (AD BC) in Java Date using SimpleDateFormat - Java
- Most Essencial AWS CLI 2 S3 ls Command Options - AWS
- How to Print the Name of a Variable in Python - Python
- How to Read a binary File with Python - Python