Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to print all the common elements of two lists.
Given two lists, we need to find and print all the common elements between them. Python provides several approaches to solve this problem efficiently.
Examples
Input : list1 = [5, 6, 7, 8, 9]
list2 = [5, 13, 34, 22, 90]
Output : {5}
Explanation
The common element between both lists is 5, which appears in both lists.
Using Set Intersection
Convert both lists to sets and use the intersection operator (&) to find common elements ?
def find_common_elements(list1, list2):
set1 = set(list1)
set2 = set(list2)
common = set1 & set2
if common:
print("Common Elements:", common)
else:
print("No common elements")
return common
# Example 1: Lists with common elements
list1 = [5, 6, 7, 8, 9]
list2 = [5, 13, 34, 22, 90]
find_common_elements(list1, list2)
# Example 2: Lists with no common elements
list3 = [1, 2, 3, 4]
list4 = [5, 6, 7, 8]
find_common_elements(list3, list4)
Common Elements: {5}
No common elements
Using List Comprehension
Find common elements using list comprehension with membership testing ?
def common_with_list_comprehension(list1, list2):
common = [item for item in list1 if item in list2]
# Remove duplicates by converting to set
common = list(set(common))
if common:
print("Common Elements:", common)
else:
print("No common elements")
return common
# Example
list1 = [1, 2, 3, 4, 5, 3]
list2 = [3, 4, 5, 6, 7, 3]
common_with_list_comprehension(list1, list2)
Common Elements: [3, 4, 5]
Using intersection() Method
Use the built-in intersection() method for more readable code ?
def common_with_intersection(list1, list2):
set1 = set(list1)
set2 = set(list2)
common = set1.intersection(set2)
if common:
print("Common Elements:", common)
else:
print("No common elements")
return common
# Example with multiple common elements
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common_with_intersection(list1, list2)
Common Elements: {3, 4, 5}
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Set Intersection (&) | O(min(len(set1), len(set2))) | Most efficient |
| List Comprehension | O(len(list1) * len(list2)) | Preserving order |
| intersection() Method | O(min(len(set1), len(set2))) | Readable code |
Conclusion
Use set intersection (&) for the most efficient solution. List comprehension is useful when you need to preserve the original order of elements. The intersection() method provides the most readable code.
Advertisements
