Python Find Index of all Occurrences in List

Last Updated On Friday 22nd Apr 2022

Python Find Index of all Occurrences in List

List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

  • The number of occurrences of an element in a list can be calculated with the help of list.count(<item>).
  • It takes the item to be counted as its argument and returns the total number of times that element appears in the list.


The count() method returns the number of occurrences of a substring in the given string.


	string.count(substring, start=..., end=...)
	items = [1, 4, 7, 8, 2, 9, 2, 1, 1, 0, 4, 3]

print(items.count(1)) # 3

Finding the index of items

  • <list>.index(<item>) will return the index number of the first occurrence of an item passed in.

Find all Indices of Element in list Python

	items = [7, 4, 1, 0, 2, 5]

print(items.index(4)) # 1

print(items.index(10)) # ValueError: 10 is not in list
  • start and end indices can also be provided to narrow the search to a specific section of the list.
	names = ["Adam", "Alice", "Ben", "Tom", "Sam", "Jane"]

names.index("Adam") # 0

names.index("Ben", 2, 5) # 3
  • You can use enumerate() in a loop in almost the same way that you use the original iterable object.
	names = ["Adam", "Alice", "Ben", "Tom", "Sam", "Jane"]

indices = [i for i, x in enumerate(names) if x == "Tom"]

print(indices) # [3]
	import numpy as np
values = np.array([ 11,22,33,12,23,45,54,56,23,82,11 ])

print(np.where(values == 11)[0]) # [ 0 10 ]