Given two lists, the task is to extract all elements that appear in both lists. For Example:
Input: a = [1, 2, 3, 4, 5], b = [4, 5, 6]
Output: [4, 5]
Let's explore different methods to print all the common elements of two lists in Python.
Using & Operator
This method converts both lists to sets and directly performs an intersection, which immediately returns all the shared values.
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
res = list(set(a) & set(b))
print(res)
Output
[4, 5]
Explanation:
- set(a) and set(b) convert lists to sets.
- set(a) & set(b) returns only the elements present in both.
- list() is used to convert the result back into a list.
Using set.intersection() Method
This method also uses sets but calls the built-in intersection() function to extract all common elements.
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
res = list(set(a).intersection(b))
print(res)
Output
[4, 5]
Explanation:
- set(a).intersection(b) checks which elements of a also appear in b.
- The returned set is converted to a list for printing.
Using List Comprehension
This method scans all elements of the first list and keeps those that also exist in the second list.
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
res = [x for x in a if x in b]
print(res)
Output
[4, 5]
Explanation:
- x in b checks if each value of a is present in b.
- Only matching values are added to the list res.
Using filter() with lambda
This approach uses filter() to keep only the elements from the first list that appear in the second.
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
res = list(filter(lambda x: x in b, a))
print(res)
Try it on GfG Practice
Output
[4, 5]
Explanation:
- lambda x: x in b checks if each value from a exists in b.
- filter() keeps matching elements and returns them as an iterable.
- list() converts the filtered results into a list.