Find common elements from two lists in Python
This post will discuss how to find common elements from two lists in Python.
1. Using intersection() function
A simple and fairly efficient solution is to convert the first list into a set and then call the intersection() function. It returns a new set with elements common to the set with another iterable.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': first = [1, 2, 3, 5] second = [2, 4, 5, 7] common = set(first).intersection(second) print(common) # {2, 5} |
2. Using bitwise comparison
You can also use the operator-based counterpart of intersection(), which happens to be bitwise, and (&) operator. But this requires both arguments to be set, as shown below:
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': first = [1, 2, 3, 5] second = [2, 4, 5, 7] common = set(first) & set(second) print(common) # {2, 5} |
3. Using List Comprehension
Finally, you can find common elements from two lists using list comprehensions by searching each element of the first list in the second list. The time complexity of this solution is quadratic, and this is definitely not a recommended solution for large lists.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': first = [1, 2, 3, 5] second = [2, 4, 5, 7] common = [x for x in first if x in second] print(common) # {2, 5} |
That’s all about finding the common elements from two lists in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)