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

Updated: June 10, 2023 By: Khue Post a comment

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.