Python List Contains – Check if Element Exists in List

How to check if an element contains/exists in a list in python? To check if an element or item exists in a list you can simply use the in operator. If an element exists the expression returns True, otherwise, returns False. Besides this, there are other functions that can be used to check.

Methods to Check if Element Contains in Python List:

  1. Python in operator to check if an element contains in a list.
  2. User count() and Counter().
  3. Use List comprehension,
  4. filter() with any() method.
  5. index() – returns an index if the element exists, use this to check if the element exists. if the element is not present, ValueError is raised.

1. Quick Examples of List Contains

Following are quick examples of how to check whether the element is present in the list or not.


# Quick Examples to check if element contains in list

# Consider list of integers
marks=[90,56,78,90,45]
print("Actual List: ",marks)

# Using if statement
if 78 in marks:
	print("Exist!")
else:
	print("Not exist!")
 
# Using count()
if(marks.count(78)>0):
	print("Exist!")
else:
	print("Not exist!")
 
# Using Counter()
from collections import Counter
if(Counter(marks)[78]>0):
	print("Exist!")
else:
	print("Not exist!")
 
# Using index() with try-except block
try:
   marks.index(78)
   print("Exist!")
except:
    print("Not exist!")

# Using any()
print(any(i==99 for i in marks))

# Using any() with filter()
print(any(list(filter(lambda x: x==30, marks))))

# Using any() with List Comprehension
print(any(i for i in marks if i == my_element))

2. Check if Python List Contains Element using in Operator

By using the in operator you can check if the element contains in the list in python. The in is the most convenient way to check whether an item exists on the list and you can use not in operator to check if the element does not exist in the list. With the in operator, if an element exists, it returns True otherwise returns False. Here, is the syntax of using an in operator with the list.


# Syntax
element in mylist

Here, the element is the value you wanted to check if it contains in the list. and mylist is the list object where you wanted to check for element existence.


# Check if element exists in list
marks=[90,56,78,90,45]
print(78 in marks) # Output: True
print(79 in marks) # Output: False

3. Use in Operator with if Statement

In real time, you would use the in operator to check whether an element exists in Python List along with the if statement.

3.1 if statement Syntax

Syntax of the if condition that uses an in operator.


# Using if statement
if my_element in mylist1:
	print("Exist!")
else:
        print("Not exist!")

Here,

  • If the element exists, the condition will become True and statements inside if block are executed.
  • If the element doesn’t exist, the condition will become False and statements inside the else block are executed.

3.2 if statement Example

Let’s have a list with some integers and check whether the element 78 exists in the list or not.


# Consider list of integers
marks=[90,56,78,90,45]
print("Actual List: ",marks)

my_element=78

# Using if statement
if my_element in marks:
	print("Exist!")
else:
	print("Not exist!")
 
# Output:
# Actual List:  [90, 56, 78, 90, 45]
# Exist!

The example print Exists! as element value 78 contains in the list (if block is executed).

4. Use count() to Check if Python List Contains Element

the count() method will show the number of times it occurs in the entire list, in other words count() method is used to return the total occurrences of the given element from the list, if the occurrence count of our specified element is greater than 0, we can say that our element exists in the list.

4.1 count() Syntax

The syntax for the count(). Here, mylist1 is the input list and my_element is the element which you wanted to check if it exists or contains in the python list named mylist1.


# Using count()
if(mylist1.count(my_element)>0):
	  print("Exist!")
else:
	print("Not exist!")

4.2 count() Example

Let’s have a list with some strings and check whether “japan” exists in the list or not using the count() method.


# Consider list of strings
countries=["india","japan","china","russia","france"]

my_element="japan"

# Using count()
if(countries.count(my_element)>0):
	  print("Exist!")
else:
	print("Not exist!")
 
# Output:
# Exist!

As the “japan” exists in the list, if block is executed and prints the Exist! to console.

5. Use Counter() to Check if List Contains Element

The counter() is similar to the count() method, the counter holds the data in an unordered collection which allows us to count the items in an iterable list. It is important to import counter from the collections module. Let’s use this to check if an element contains in a python list.

5.1 Counter() Syntax

The syntax of the counter().


# Syntax & usage of counter()
if(Counter(mylist1)[my_element]>0):
	print("Exist!")
else:
	print("Not exist!")

5.2 counter() Example with Python List Contains

Let’s have a list with some strings and check whether some elements exist in this list or not using the counter() method.


from collections import Counter
# Consider list of strings
countries=["india","japan","china","russia","france"]

my_element="russia"

# Using Counter()
if(Counter(countries)[my_element]>0):
	  print("Exist!")
else:
	print("Not exist!")
 
my_element="USA"
 # Using Counter()
if(Counter(countries)[my_element]>0):
	  print("Exist!")
else:
	print("Not exist!")
 
# Output:
# Exist!
# Not exist!

Here, “russia” exists in the list hence, if block is executed and “USA” doesn’t exist in the list hence else block is executed.

6. Using index() to Check List Exists or Not

The Python list index() method will return the index position of an element by taking the element as a parameter, if the element exists, it will return the index, otherwise, ValueError is raised. To handle this error, we have to use the try-except block and use this method inside the try block. We can specify error messages in the except block.

6.1 index() Syntax

The syntax for the list index() method.


# Using index() with try-except block
try:
   mylist1.index(my_element)
   print("Exist!")
except:
    print("Not exist!")

6.2 List Contains Example using index

Let’s have a list with some strings and check whether some elements exist in this list or not using the index() method.

Here, item 12 exists in the list so no exception is raised from the try block and item 800 doesn’t exist in the list so an error is raised, and the catch block is executed.


# Consider list of integers
marks=[12,43,56,78,54,33,22]

# Using index() with try-except block
try:
   marks.index(12)
   print("Exist!")
except:
    print("Not exist!")

# Using index() with try-except block
try:
   marks.index(800)
   print("Exist!")
except:
    print("Not exist!")

# Output:
# Exist!
# Not exist!

7. Using any() to Check List Contains Element

7.1 any() with for loop

The any() function in python can be used to check if the element contains in a list. we will check if our element is equal to any one of the elements in the list or not using this method by iterating the list using for loop.

  1. If at least one element matches with an element, True is returned.
  2. If no element is matched, False is returned.

Example: Let’s have a list with some integers and check whether some elements exist in this list or not by passing for loop to iterate all elements and == operator to check each element.


# Consider list of integers
marks=[12,43,56,78,54,33,22]

# using any()
print(any(i==12 for i in marks))
print(any(i==45 for i in marks))

# Output:
# True
# False

Explanation:

  • Element 12 exists in the list, so True is returned.
  • Element 45 doesn’t exist in the list, so False is returned.

7.2 any() with filter()

Inside this method, we can pass a lambda expression as the first parameter for specifying the condition and the second parameter as the input list. The operator used inside the expression is == (Equal to) operator. So all the matched elements are filtered and stored in a list. If the list contains at least one element, any() will return True. Otherwise False is returned.

Example: Let’s have a list with some integers and check whether some elements exist in this list or not by passing the filter() function.


# Consider list of integers
marks=[12,43,56,78,54,33,22]

# Using any() with filter()
print(any(list(filter(lambda x: x==30, marks))))
print(any(list(filter(lambda x: x==22, marks))))

# Output:
# False
# True

Explanation:

  • Element 30 doesn’t exist in the list, so False is returned.
  • Element 22 exists in the list, so True is returned.

7.3 any() with List comprehension

We will pass list comprehension inside any() method. First, we will iterate the list and check if the iterator is equal to our element or not using the if condition. If exists, it is stored in a list, otherwise, it will be ignored, If the list contains at least one element, any() will return True, otherwise False is returned.

Example: Let’s have a list with some integers and check whether some elements exist in this list or not by passing list comprehension.


# Consider list of integers
marks=[12,43,56,78,54,33,22]

# Using any() with List Comprehension
print(any(i for i in marks if i == 12))
print(any(i for i in marks if i == 60))

# Output:
# True
# False

Explanation:

  • Element 12 contains in the list, so True is returned.
  • Element 60 doesn’t exist in the list, so False is returned.

8. Conclusion

In this article, you have learned how to check if the element contains in the list in python by using in operator, which checks if an element exists in the list or not. if it exists it returns True otherwise, returns False. Besides this, you can also use the count(), counter(), index, and any. When you use the index, it returns an error if the element is not found hence, it’s good practice to use try-except.

References

Leave a Reply