Sling Academy
Home/Python/Python: How to Find All Occurrences of a Value in a List

Python: How to Find All Occurrences of a Value in a List

Last updated: June 10, 2023

This concise, straightforward article will walk you through a few different ways to find all occurrences of a certain value in a list in Python. The desired result will be a list of indices of found elements. Let’s get started.

Using list comprehension

You can use list comprehension with the enumerate() method to create a new list by filtering out the indices of the elements that match your condition from the original list.

Example:

games = [
    "Diablo 4", 
    "Leguge of Legends", 
    "Counter Strike", 
    "Dota 2", 
    "Minecraft", 
    "Call of Duty", 
    "Cyberpunk 2077"
]

# find indices of games that start with "C"
indices = [i for i, game in enumerate(games) if game.startswith("C")]
print(indices)

Output:

[2, 5, 6]

In case you want to get a list of values instead of a list of indices, you can do like this:

games = [
    "Diablo 4", 
    "Leguge of Legends", 
    "Counter Strike", 
    "Dota 2", 
    "Minecraft", 
    "Call of Duty", 
    "Cyberpunk 2077"
]

# find names of games that start with "C"
games_start_with_c = [game for game in games if game.startswith("C")]
print(games_start_with_c)

Output:

['Counter Strike', 'Call of Duty', 'Cyberpunk 2077']

Using a loop with the append() method

The core idea of this approach is to use a loop to iterate over the elements and their indices and appends the indices that match a certain condition to a new list:

  1. Create an empty list to store the indices.
  2. Use a loop with the enumerate() method to iterate over the elements and their indices.
  3. Use an if statement to check if the element matches the condition.
  4. If yes, append the index to the new list.

Example:

# Create a list of numbers
words = [
    "Sling Academy",
    "Python",
    "Programming",
]

# Create an empty list to store the indices
indices = []

# Iterate over the elements and their indices
for i, x in enumerate(words):
    # Check if the element's length is greater than 10
    if len(x) > 10:
        # If yes, append the index to the new list
        indices.append(i)

# Print the new list
print(indices)

Output:

[0, 2]

This is a common method used in other programming languages like JavaScript or Dart. However, in Python, I think using list comprehension is more concise and elegant.

Next Article: How to Reverse a List in Python (with Examples)

Previous Article: Python: How to Remove Elements from a List (4 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