Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Python List index() – How to Find Element Positions with Practical Examples

Python lists are ordered collections that can hold items of any data type—integers, strings, booleans, nested lists, and more. The built‑in list.index() method is the quickest way to locate an element’s position within that sequence. Below you’ll find a step‑by‑step guide, complete with code snippets and alternative techniques for retrieving indices, even when an element appears multiple times.

Understanding list.index()

The list.index() method returns the lowest index at which a specified value appears. If the value is not present, it raises a ValueError. For reference, see the official Python documentation.

Syntax

list.index(element, start=0, end=len(list))

Parameters

ParameterDescription
elementThe value you want to locate.
startOptional. Start searching from this index. Default is 0.
endOptional. Stop searching before this index. Default is the list’s length.

Return Value

Returns the integer index of the first matching element. Raises ValueError if the element is absent.

Example: Basic Usage

my_list = ['A', 'B', 'C', 'D', 'E', 'F']
print("Index of 'C':", my_list.index('C'))  # 2
print("Index of 'F':", my_list.index('F'))  # 5

Example: Using start and end

my_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
print("Index of 'C' between 1 and 5:", my_list.index('C', 1, 5))  # 2
print("Index of 'F' between 3 and 7:", my_list.index('F', 3, 7))  # 5
print("Index of 'D' starting from 1:", my_list.index('D', 1))      # 3

Example: Element Not Found

my_list = ['A', 'B', 'C', 'D']
try:
    my_list.index('Z')
except ValueError as e:
    print(e)  # 'Z' is not in list

Retrieving All Indices for a Repeated Element

When a value occurs multiple times, list.index() only returns the first position. Below are several approaches to capture every index.

Using a For‑Loop

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
indices = []
for i, val in enumerate(my_list):
    if val == 'Guru':
        indices.append(i)
print(indices)  # [0, 3, 6]

Using a While‑Loop with index()

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
indices = []
next_index = -1
while True:
    try:
        next_index = my_list.index('Guru', next_index + 1)
        indices.append(next_index)
    except ValueError:
        break
print(indices)  # [0, 3, 6]

List Comprehension

indices = [i for i, val in enumerate(my_list) if val == 'Guru']
print(indices)  # [0, 3, 6]

Using enumerate()

indices = [i for i, val in enumerate(my_list) if val == 'Guru']
print(indices)  # [0, 3, 6]

Using filter()

indices = list(filter(lambda i: my_list[i] == 'Guru', range(len(my_list))))
print(indices)  # [0, 3, 6]

Advanced Techniques

NumPy for Large Data Sets

When working with numeric or large textual data, converting the list to a NumPy array can speed up searches.

pip install numpy
import numpy as np
my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
array = np.array(my_list)
indices = np.where(array == 'Guru')[0]
print(indices)  # [0 3 6]

more_itertools.locate()

For a clean, functional approach, more_itertools.locate() returns an iterator of indices that satisfy a predicate.

pip install more_itertools
from more_itertools import locate
indices = list(locate(my_list, lambda x: x == 'Guru'))
print(indices)  # [0, 3, 6]

Key Takeaways

Python

  1. Python List Operations: Creation, Access, Modification, and Advanced Techniques
  2. Mastering std::list in C++: Syntax, Functions & Practical Examples
  3. Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples
  4. Python Counter in collections – Efficient Counting, Updating, and Arithmetic Operations
  5. Creating ZIP Archives in Python: From Full Directory to Custom File Selection
  6. Python list.count(): Expert Guide with Practical Examples
  7. How to Remove Items from a Python List: remove(), pop(), clear(), and del
  8. Python Calendar Module: Expert Guide with Code Examples
  9. Master Python Multithreading: GIL Explained with Practical Examples
  10. Mastering Python Lists: A Comprehensive Guide