![]() |
VOOZH | about |
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.
This method converts both lists to sets and directly performs an intersection, which immediately returns all the shared values.
[4, 5]
Explanation:
This method also uses sets but calls the built-in intersection() function to extract all common elements.
[4, 5]
Explanation:
This method scans all elements of the first list and keeps those that also exist in the second list.
[4, 5]
Explanation:
This approach uses filter() to keep only the elements from the first list that appear in the second.
[4, 5]
Explanation: