Sling Academy
Home/Python/Python: Checking If a List Contains an Element (3 Approaches)

Python: Checking If a List Contains an Element (3 Approaches)

Last updated: June 16, 2023

This concise, example-based article will walk you through 3 different ways to check whether a Python list contains an element. There’s no time to waste; let’s get started!

Using the “in” operator

This solution uses the in operator to check if an element is in a list. It returns True if the element is found and False otherwise.

# define a list with different data types
my_list = [1, 2, 3, ['a', 'b', 'c'], {'sling': 'academy'}]

print(2 in my_list) # True
print(['a', 'b', 'c'] in my_list) # True
print({'sling': 'academy'} in my_list) # True
print('turtle' in my_list) # False

The code is concise and intuitive. It also works for any type of element, even if they are not hashable or mutable.

Using the list.index() method

This solution uses the index() method to find the index of the first occurrence of an element in a list. It returns the index as an integer if the element is found and raises a ValueError exception otherwise.

Example:

# define a list with different data types
my_list = [1, 2, 3, ['a', 'b', 'c'], {'sling': 'academy'}]

try:
    index = my_list.index(3)
    print(f"'3' found at index {index}")
except ValueError:
    print('Value not found in list')

Output:

'3' found at index 2

This approach requires handling a potential exception, but it provides information about the index of the element in the list (if found).

Using the list.count() method

Another working solution is to use the list.count() method to count the occurrences of an element in a list and check if it’s greater than zero.

Example:

my_list = [1, 2, 3, 4, 5, 3, 4, 3, 3]
element = 3

count = my_list.count(element)

if count > 0:
    print(f'Element {element} is in the list {count} times')
else:
    print(f'Element {element} is not in the list')

Output:

Element 3 is in the list 4 times

If the list is large, this approach is less efficient than the preceding ones because it requires traversing the entire list to count occurrences.

Next Article: Shuffling a List in Python (4 Approaches)

Previous Article: Python: How to Compare 2 Lists (3 Approaches)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types