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

  • 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