Find all indices of elements in a list in Python
In Python, lists are used to store multiple elements under one name. Each element can be accessed by its position in the list. An element can appear in multiple positions in a list.
In this tutorial, we will see how to find the index of all occurrences of a particular element in a list. We will find all the indices of the element in the following list 1
.
l1 = [1, 5, 1, 8, 9, 15, 6, 2, 1]
Use for
loop to find the indices of all occurrences of an element
We can easily iterate over a list and compare each element with the required element and find its index. We can store the final result in a new list. In the following example, we use range()
the iterate function to iterate over a list.
l1 = [1, 5, 1, 8, 9, 15, 6, 2, 1]
pos = []
x = 1 # The required element
for i in range(len(l1)):
if l1[i] == x:
pos.append(i)
print(pos)
Output:
[0, 2, 8]
A more efficient and compact way to implement the above code is to use the following list comprehension.
l1 = [1, 5, 1, 8, 9, 15, 6, 2, 1]
pos = [i for i in range(len(l1)) if l1[i] == 1]
print(pos)
Output:
[0, 2, 8]
Similarly, we can also use enumerate()
the function to return the index and value together. For example
l1 = [1, 5, 1, 8, 9, 15, 6, 2, 1]
pos = [i for i, x in enumerate(l1) if x == 1]
print(pos)
Output:
[0, 2, 8]
numpy.where()
Find the index of all occurrences of an element in Python
using the
NumPy
The library has where()
a function that returns the index of an element in an array based on some condition. To this method, we have to pass the list as an array. The final result also comes in the form of an array. The following code snippet shows how we can use this method.
import numpy as np
l1 = [1, 5, 1, 8, 9, 15, 6, 2, 1]
pos = np.where(np.array(l1) == 1)[0]
print(pos)
Output:
[0 2 8]
Use more_itertools.locate()
the function to find the indices of all occurrences of an element
more_itertools
is a third-party convenience module. It has many functions to create efficient and compact code when processing iterable elements. locate()
The function in this module returns True
the index of the element where the condition is . It returns a itertools
object. The following code snippet explains how we can use this method.
from more_itertools import locate
l1 = [1, 5, 1, 8, 9, 15, 6, 2, 1]
pos = list(locate(l1, lambda x: x == 1))
print(pos)
Output:
[0, 2, 8]
We use list()
the function to ensure that the final result is in the form of a list.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Finding a string in a list in Python
Publish Date:2025/05/09 Views:75 Category:Python
-
This tutorial shows you how to find elements from a Python list that have a specific substring in them. We will use the following list and extract ack the strings that have in it. my_list = [ "Jack" , "Mack" , "Jay" , "Mark" ] for Find elem
Getting list shape in Python
Publish Date:2025/05/09 Views:139 Category:Python
-
In Python, knowing the shape of a list is very important for working with data structures, especially when it comes to multidimensional or nested lists. This article explores various ways to determine the shape of a list in Python, from sim
Adding multiple elements to a list in Python
Publish Date:2025/05/09 Views:180 Category:Python
-
List is a mutable data structure in Python. It can contain values of different types. This article will discuss some methods to append single or multiple elements to a Python list. append() Append a single element in a Python list usi
Get the index of the maximum and minimum values in a list in Python
Publish Date:2025/05/09 Views:117 Category:Python
-
In this tutorial, we will discuss methods to get the index of the maximum and minimum value of a list in Python. max() Get the index of the maximum value in a list using and list.index() functions in Python max() The function gives the maxi
List of numbers from 1 to N in Python
Publish Date:2025/05/09 Views:116 Category:Python
-
This tutorial will discuss how to create a list of numbers from 1 to some specified number. Create a user-defined function to create a list of numbers from 1 to N This method will take the desired number from the user and for iterate until
Convert List to Pandas DataFrame in Python
Publish Date:2025/05/09 Views:133 Category:Python
-
This article will show you how to convert items in a list into a Pandas DataFrame. Convert List to Pandas DataFrame in Python DataFrame, in general, is a two-dimensional labeled data structure. Pandas is an open source Python package that i
Sorting a list by another list in Python
Publish Date:2025/05/09 Views:148 Category:Python
-
Normally, when we sort a list, we do it in ascending or descending order. However, we can sort a list based on the order of another list in Python. We will learn how to sort a given list based on the values in another list in this art
Normalizing a list of numbers in Python
Publish Date:2025/05/09 Views:134 Category:Python
-
Normalization means converting the given data to another scale. We rescale the data so that it is between two values. Most of the time, the data is rescaled between 0 and 1. We rescale data for different purposes. For example, machine learn
How to create a list of a specific size in Python
Publish Date:2025/05/09 Views:195 Category:Python
-
Preallocating storage for a list or array is a common practice among programmers when they know the number of elements in advance. Unlike C++ and Java, in Python you must initialize all preallocated storage with some value. Typically, devel