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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots