Skip to content

Python: Find List Index of All Occurrences of an Element

Python Find List Index of All Occurences of an Element Cover Image

In this tutorial, you’ll learn how to use Python to find the list index of all occurrences of an element. In many cases, Python makes it simple to find the first index of an element in a list. However, because Python lists can contain duplicate items, it can be helpful to find all of the indices of an element in a list.

By the end of this tutorial, you’ll have learned:

  • How to find the indices of all occurences of an element in a Python list using:
    • For loops,
    • List comprehensions,
    • NumPy, and
    • more_itertools
  • Which method is fastest

Let’s get started!

Table of Contents

How Python List Indices Work

Before diving into how to get the index positions of all elements in a Python list, let’s take a quick moment to understand how Python lists are indexed. Because Python lists are ordered container objects, their order remains unless it’s explicitly altered.

Python list indices start at 0 and continue through to the length of the list minus one. The image below shows how these list indices work in Python:

How does Python List Indexing Work
Python List Indexing Explained

In the following section, you’ll learn how to use the list .index() method to find the index of an element in the list.

How the Python List Index Method Works

The Python list .index() has three parameters:

  1. The element to search for,
  2. The index to begin searching at, and
  3. The index to search up to

The only required argument is the element to search for. By default, Python will search through the entire list, unless explicitly told otherwise.

Let’s take a look at how this method looks :

# The list.index() Method
list.index(
    value=,     # The value to search for
    start=,     # The index to start at
    stop=       # The index to end at
)

Let’s take a look at an example. We can load a list with different elements in it and find the index of the element using the .index() method:

# Using the .index() Method
a_list = [1,2,3,4,1,2,1,2,3,4]
print(a_list.index(1))

# Returns: 0

In the example above, we applied the .index() method on our list to find the index of the element 1. The method returned the value 0, meaning the item exists at the 0th position. However, we know that the value exists multiple times in the list.

Why didn’t the method return more than the first index? This is how the method works. Even if an item exists more than once, only the first instance is returned.

In the following sections, you’ll learn how to get the index positions of all occurrences of an element in a list.

How to Get Index of All Occurrences of Element in a Python List with a For Loop and Enumerate

One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.

Because of this, we can check whether the element matches the element we want to find. If it does, we can add the index position to another list. Let’s see how this works with an example:

# Using enumerate to Find Index Positions
a_list = [1,2,3,4,1,2,1,2,3,4]
def find_indices(list_to_check, item_to_find):
    indices = []
    for idx, value in enumerate(a_list):
        if value == item_to_find:
            indices.append(idx)
    return indices

print(find_indices(a_list, 1))

# Returns: [0, 4, 6]

Let’s break down what we did here:

  1. We defined a function that takes a list and an element as input
  2. The function then loops over the retult of the enumerate() function
  3. If the value of the item matches the item we’re looking for, the corresponding index is appended to the list
  4. Finally, the list of all indices is returned

How to Get Index of All Occurrences of Element in a Python List with more_itertools

The built-in more_itertools library comes with a number of helpful functions. One of these functions is the locate() function that takes an iterable and a function to evaluate against.

In order to find the index positions of all elements matching an element, we can use a lambda function that simply checks if that item is equal to the item we want to check against.

Let’s take a look at an example:

# Using more_itertools to Find All Occurrences of an Element
from more_itertools import locate
a_list = [1,2,3,4,1,2,1,2,3,4]
def find_indices(list_to_check, item_to_find):
    indices = locate(list_to_check, lambda x: x == item_to_find)
    return list(indices)
    
print(find_indices(a_list, 1))

# Returns: [0, 4, 6]

Let’s break down what we did here:

  1. We defined a function that takes both a list and the element to search for
  2. The function uses the locate() function to use the list we want to search and a lambda function that checks if each item is equal to the value we’re searching for
  3. Finally, the function returns a list of the result

How to Get Index of All Occurrences of Element in a Python List with Numpy

NumPy makes the process of finding all index positions of an element in a list very easy and fast. This can be done by using the where() function. The where() function returns the index positions of all items in an array that match a given value.

Let’s take a look at an example:

# Using numpy to Find All Occurrences of an Element
import numpy as np

a_list = [1,2,3,4,1,2,1,2,3,4]
def find_indices(list_to_check, item_to_find):
    array = np.array(list_to_check)
    indices = np.where(array == item_to_find)[0]
    return list(indices)

print(find_indices(a_list, 1))

# Returns: [0, 4, 6]

Let’s break down what we did here:

  1. We created a function that takes a list and an element to find
  2. The list is converted into a numpy array
  3. The where() function is used to evaluated the array against our item
  4. We return the 0th index of that resulting array
  5. We convert that array to a list

How to Get Index of All Occurrences of Element in a Python List with a List Comprehension

In this section, we’ll take a look at how to use a list comprehension to return a list of indices of an element in a list. This method works the same as the first method, the for loop, except it uses a list comprehension.

Let’s see how we can convert the for loop into a list comprehension:

# Using a List Comprehension to Find All Occurrences of an Element
a_list = [1,2,3,4,1,2,1,2,3,4]
def find_indices(list_to_check, item_to_find):
    return [idx for idx, value in enumerate(list_to_check) if value == item_to_find]

print(find_indices(a_list, 1))

# Returns: [0, 4, 6]

The method shown above is much cleaner and easier to read than the for loop. In the next section, we’ll take a look at how these different methods compare in terms of speed.

Which Method is Fastest To Get Index of All Occurrences of an Element in a Python List

The table below breaks down how long each method took to find the indices of all occurrences in a list of one hundred million elements:

MethodTime to execute
For loop and enumerate()4.97 seconds
more_itertools locate()7.08 seconds
numpy where()6.05 seconds
List Comprehension and enumerate()4.69 seconds
The execution time of each of these methods

We can see that the list comprehension method was the fastest. Not only was this method the fastest, but it was very easy to read and required no additional packages.

Comparing Methods of Runtimes for Finding Indices of all Occurrences of an Element in a List

Conclusion

In this tutorial, you learned how to find the index positions of all occurrences of an element in a Python list. You learned how to do this using the Python enumerate() function using both for loops and list comprehensions. You also learned how to use the numpy where() function to do and the more_itertools locate() function.

Additional Resources

To learn more about related topics, check out the tutorials below:

  • Python List Index: Find First, Last or All Occurrences
  • Python IndexError: List Index Out of Range Error Explained
  • Python: Get Index of Max Item in List

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials. View Author posts

Tags: Numpy Python Python Lists

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Python in 30 days cover image

Learn Python in 30 days. For free.

.

哆哆女性网雪中悍刀行青鸟结局是什么冯姓男孩起名字满分名字洛阳网站建设开发《活着》观后感济南seo网络优化范爱农读后感50字本月运势seo优化成本起名字谭面馆怎么起名好听的面馆名字大全东莞seo服务公司六一儿童节的作文怎么写海报制作网站排名22sssseo智能软件安阳周易研究会26uuuu最新亚洲影视极地守护犬华文中宋字体免费下载北海附近的美食特色韩剧最新电视剧大全百度seo是什么永城现代牙科周易与预测学在线阅读公司起名 蔬菜速度与激情7电影天堂测试孩子起名大全梦想城镇破解版免费公司起名字怎么查微信起名大全女霸气淀粉肠小王子日销售额涨超10倍罗斯否认插足凯特王妃婚姻不负春光新的一天从800个哈欠开始有个姐真把千机伞做出来了国产伟哥去年销售近13亿充个话费竟沦为间接洗钱工具重庆警方辟谣“男子杀人焚尸”男子给前妻转账 现任妻子起诉要回春分繁花正当时呼北高速交通事故已致14人死亡杨洋拄拐现身医院月嫂回应掌掴婴儿是在赶虫子男孩疑遭霸凌 家长讨说法被踢出群因自嘲式简历走红的教授更新简介网友建议重庆地铁不准乘客携带菜筐清明节放假3天调休1天郑州一火锅店爆改成麻辣烫店19岁小伙救下5人后溺亡 多方发声两大学生合买彩票中奖一人不认账张家界的山上“长”满了韩国人?单亲妈妈陷入热恋 14岁儿子报警#春分立蛋大挑战#青海通报栏杆断裂小学生跌落住进ICU代拍被何赛飞拿着魔杖追着打315晚会后胖东来又人满为患了当地回应沈阳致3死车祸车主疑毒驾武汉大学樱花即将进入盛花期张立群任西安交通大学校长为江西彩礼“减负”的“试婚人”网友洛杉矶偶遇贾玲倪萍分享减重40斤方法男孩8年未见母亲被告知被遗忘小米汽车超级工厂正式揭幕周杰伦一审败诉网易特朗普谈“凯特王妃P图照”考生莫言也上北大硕士复试名单了妈妈回应孩子在校撞护栏坠楼恒大被罚41.75亿到底怎么缴男子持台球杆殴打2名女店员被抓校方回应护栏损坏小学生课间坠楼外国人感慨凌晨的中国很安全火箭最近9战8胜1负王树国3次鞠躬告别西交大师生房客欠租失踪 房东直发愁萧美琴窜访捷克 外交部回应山西省委原副书记商黎光被逮捕阿根廷将发行1万与2万面值的纸币英国王室又一合照被质疑P图男子被猫抓伤后确诊“猫抓病”

哆哆女性网 XML地图 TXT地图 虚拟主机 SEO 网站制作 网站优化