How to Check If an Element Exists in Two Lists in Python
In Python, you may encounter situations where you want to check if an element exists in two different lists.
You can use various methods such as intersection()
, in
operator, and list comprehension in Python for checking if an an element exists in two different lists.
Method 1: Using Set and Intersection
set(list1).intersection(list2)
Method 2: Using in
operator
if ele in list1 and ele in list2:
print(ele)
Method 3: Using list comprehension
[ele for x in [ele] if x in list1 and x in list2]
The following examples demonstrate how to use intersection()
, in
operator, and list comprehension methods for checking if an an element exists in two different lists.
Example 1: Using Set and Intersection
You can use set()
and intersection()
functions to check if an element exists in two different lists.
The set()
creates an unordered collection of unique elements and the intersection()
function returns the set of common elements between two sets.
# create lists
list1 = ['a', 'b', 'c']
list2 = ['x', 'a', 'z']
# find common element between two lists
print(set(list1).intersection(list2))
# output
{'a'}
You can see that a
element exists in list1
and list2
.
This method is a more concise way to for checking if an element exists in two different lists.
Example 2: Using in
operator
You can also use in
operator to check if an element exists in two different lists.
# create Lists
list1 = ['a', 'b', 'c']
list2 = ['x', 'a', 'z']
# check common element between two lists
ele = 'a'
if ele in list1 and ele in list2:
print(ele)
# output
a
You can see that a
element exists in list1
and list2
.
This method is more basic and involves the if statement to check if an element exists in two different lists.
Example 3: Using list comprehension
You can also use list comprehension to check if an element exists in two different lists.
# create Lists
list1 = ['a', 'b', 'c']
list2 = ['x', 'a', 'z']
# find common element between two lists
ele = 'a'
print([ele for x in [ele] if x in list1 and x in list2])
# output
['a']
You can see that a
element exists in list1
and list2
.
This method is a more basic and involves the list comprehension to check if an element exists in two different lists. The syntax may look complex, but it is more useful tool in Python for list operations.