>>> ["foo", "bar", "baz"].index("bar")
1

See the documentation for the built-in .index() method of the list:

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Caveats

Linear time-complexity in list length

An index call checks every element of the list in order, until it finds a match. If the list is long, and if there is no guarantee that the value will be near the beginning, this can slow down the code.

This problem can only be completely avoided by using a different data structure. However, if the element is known to be within a certain part of the list, the start and end parameters can be used to narrow the search.

For example:

>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514

The second call is orders of magnitude faster, because it only has to search through 10 elements, rather than all 1 million.

Only the index of the first match is returned

A call to index searches through the list in order until it finds a match, and stops there. If there could be more than one occurrence of the value, and all indices are needed, index cannot solve the problem:

>>> [1, 1].index(1) # the `1` index is not found.
0

Instead, use a list comprehension or generator expression to do the search, with enumerate to get indices:

>>> # A list comprehension gives a list of indices directly:
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> # A generator comprehension gives us an iterable object...
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> # which can be used in a `for` loop, or manually iterated with `next`:
>>> next(g)
0
>>> next(g)
2

The list comprehension and generator expression techniques still work if there is only one match, and are more generalizable.

Raises an exception if there is no match

As noted in the documentation above, using .index will raise an exception if the searched-for value is not in the list:

>>> [1, 1].index(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 2 is not in list

If this is a concern, either explicitly check first using item in my_list, or handle the exception with try/except as appropriate.

The explicit check is simple and readable, but it must iterate the list a second time. See What is the EAFP principle in Python? for more guidance on this choice.

Answer from Alex Coventry on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-list-index
Python List index() - Find Index of Item - GeeksforGeeks
Explanation: index("dog") method finds the first occurrence of "dog" in the list a. Since "dog" is at index 1, it returns 1. ... The first index of element in the list within the specified range.
Published   April 27, 2025
Top answer
1 of 16
6115
>>> ["foo", "bar", "baz"].index("bar")
1

See the documentation for the built-in .index() method of the list:

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Caveats

Linear time-complexity in list length

An index call checks every element of the list in order, until it finds a match. If the list is long, and if there is no guarantee that the value will be near the beginning, this can slow down the code.

This problem can only be completely avoided by using a different data structure. However, if the element is known to be within a certain part of the list, the start and end parameters can be used to narrow the search.

For example:

>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514

The second call is orders of magnitude faster, because it only has to search through 10 elements, rather than all 1 million.

Only the index of the first match is returned

A call to index searches through the list in order until it finds a match, and stops there. If there could be more than one occurrence of the value, and all indices are needed, index cannot solve the problem:

>>> [1, 1].index(1) # the `1` index is not found.
0

Instead, use a list comprehension or generator expression to do the search, with enumerate to get indices:

>>> # A list comprehension gives a list of indices directly:
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> # A generator comprehension gives us an iterable object...
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> # which can be used in a `for` loop, or manually iterated with `next`:
>>> next(g)
0
>>> next(g)
2

The list comprehension and generator expression techniques still work if there is only one match, and are more generalizable.

Raises an exception if there is no match

As noted in the documentation above, using .index will raise an exception if the searched-for value is not in the list:

>>> [1, 1].index(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 2 is not in list

If this is a concern, either explicitly check first using item in my_list, or handle the exception with try/except as appropriate.

The explicit check is simple and readable, but it must iterate the list a second time. See What is the EAFP principle in Python? for more guidance on this choice.

2 of 16
725

The majority of answers explain how to find a single index, but their methods do not return multiple indexes if the item is in the list multiple times. Use enumerate():

for i, j in enumerate(['foo', 'bar', 'baz']):
    if j == 'bar':
        print(i)

The index() function only returns the first occurrence, while enumerate() returns all occurrences.

As a list comprehension:

[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'bar']

Here's also another small solution with itertools.count() (which is pretty much the same approach as enumerate):

from itertools import izip as zip, count # izip for maximum efficiency
[i for i, j in zip(count(), ['foo', 'bar', 'baz']) if j == 'bar']

This is more efficient for larger lists than using enumerate():

$ python -m timeit -s "from itertools import izip as zip, count" "[i for i, j in zip(count(), ['foo', 'bar', 'baz']*500) if j == 'bar']"
10000 loops, best of 3: 174 usec per loop
$ python -m timeit "[i for i, j in enumerate(['foo', 'bar', 'baz']*500) if j == 'bar']"
10000 loops, best of 3: 196 usec per loop
Discussions

Get index in the list of objects by attribute in Python - Stack Overflow
I have list of objects with attribute id and I want to find index of object with specific id. I wrote something like this: Copyindex = -1 for i in range(len(my_list)): if my_list[i].id == 'specific_id' index = i break · but it doesn't look very well. Are there any better options? ... Looping by index is a really huge anti-pattern in Python ... More on stackoverflow.com
🌐 stackoverflow.com
How to find the index of something in a list without knowing the full item
Loop through list, check if 'ham' in item. More on reddit.com
🌐 r/learnpython
7
1
March 29, 2021
__getitem__ method in 2D array class.
The signature of __getitem__ is __getitem__(self, key) which means that the signature of your function is not valid. Since __getitem__ only accepts a single key, and you need to provide row and col to index into your two-dimensional array, you have two choices: bundle up row and col in a tuple (ie as a single value), or if you want to be able to use something like myarray[x][y], you need to think about how that would be implemented. Some clues. Version one, using a tuple: def __getitem__(self, row_col_as_tuple): row = .... ? col = .....? #How would you obtain `row` and `column` from `row_col_as_tuple`? return ?? Version two, allowing list-like access eg myarray[1][2]. Think what this is actually doing; it first calls myarray[1] and then calls [2] on whatever myarray[1] returns. That is, it is actually making two calls to __getitem__, and consequently, whatever object __getitem__ returns, that object itself must be a class that with a __getitem__ method. def __getitem__(self, key): # where `key` in an integer value = self._arr[?] return ?? # Here you have to return a class with a __getitem__ method that has access to `self._arr`. More on reddit.com
🌐 r/learnpython
5
3
September 26, 2014
How to delete from a deque in constant time without "pointers"?

There's a technique which I call 'lazy popping' which can help here.

The idea is that you don't delete immediately from the queue. Rather, you leave deleted items in the queue, but mark them as deleted in another data structure -- usually a set. Whenever you have to pop an item to execute, keep popping until you reach an item that hasn't yet been deleted.

This gives you constant-time push, amortized constant-time pop (although you may pop multiple deleted items off the queue each time you pop an item to execute, each item only gets popped exactly once) , and constant-time deletion, which is better than what you can get by maintaining a list and deleting from start or middle.

In this case, you'd save the IDs of deleted items in the set. It looks like this (untested code):

import collections

class DeletableQueue:
    def __init__(self):
        self.deleted = set()
        self.queue = collections.deque()
    def push(self, item):
        self.queue.append(item)
    def pop(self):
        # Precondition: there is at least one non-deleted item on the queue.
        while id(q[0]) in deleted:
            q[0].pop_left()  # Discard an already-deleted item.
        return q.pop_left()  # Return the actual item to pop
    def delete(self, item_to_delete):
        self.deleted.add(id(item_to_delete))
More on reddit.com
🌐 r/learnpython
15
6
October 20, 2014
🌐
Programiz
programiz.com › python-programming › methods › list › index
Python List index()
The index() method returns the index of the given element in the list.
🌐
freeCodeCamp
freecodecamp.org › news › python-find-in-list-how-to-find-the-index-of-an-item-or-element-in-a-list
Python Find in List – How to Find the Index of an Item or Element in a List
February 24, 2022 - Use the index() method to find the index of an item 1.Use optional parameters with the index() method · Get the indices of all occurrences of an item in a list · Use a for-loop to get indices of all occurrences of an item in a list · Use ...
🌐
TutorialsPoint
tutorialspoint.com › article › get-index-in-the-list-of-objects-by-attribute-in-python
Get index in the list of objects by attribute in Python
March 27, 2026 - def find_index_by_attribute(obj_list, attr_name, attr_value): """Find index of object by attribute value""" for i, obj in enumerate(obj_list): if getattr(obj, attr_name) == attr_value: return i return None class Student: def __init__(self, name, grade): self.name = name self.grade = grade students = [ Student("Emma", "A"), Student("Liam", "B"), Student("Olivia", "A+") ] # Find student by name index = find_index_by_attribute(students, "name", "Liam") print(f"Liam is at index: {index}") # Find student by grade grade_index = find_index_by_attribute(students, "grade", "A+") print(f"Student with A+ grade is at index: {grade_index}")
🌐
TutorialsPoint
tutorialspoint.com › How-to-find-the-index-of-an-object-available-in-a-list-in-Python
Python List index() Method
September 22, 2022 - Following is the syntax for the Python List index() method − ... This method returns the first index in the list at which the object is found.
🌐
StrataScratch
stratascratch.com › blog › how-to-get-the-index-of-an-item-in-a-list-in-python
How to Get the Index of an Item in a List in Python - StrataScratch
September 6, 2024 - Otherwise, Python raises a ValueError. However, it will break your program if it is not handled correctly. ... Consider you are reading sensor readings and want to get the first occurrence of a specific type of reading. You should try catching it here so the program will not crash and produce an error if no such reading exists. sensor_readings = [50, 55, 60, 65, 70] def find_reading_index(reading, readings): try: return readings.index(reading) except ValueError: return "Reading not found in the list" result = find_reading_index(65, sensor_readings) print(result) result_not_found = find_reading_index(75, sensor_readings) print(result_not_found)
Find elsewhere
🌐
DataCamp
datacamp.com › tutorial › python-list-index
Python List index() Method Explained with Examples | DataCamp
March 28, 2025 - Master Python for data science and gain in-demand skills. ... The method index() returns the lowest index in the list where the element searched for appears. ... If any element which is not present is searched, it returns a ValueError. list_numbers = [4, 5, 6, 7, 8, 9, 10] element = 3 # Not ...
🌐
Python Examples
pythonexamples.org › python-find-index-of-item-in-list
How to find index of an item in a list?
To find the index of a specific element in a given list in Python, you can call the list.index() method on the list object and pass the specific element as argument.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Find the Index of an Item in a List in Python | note.nkmk.me
July 27, 2023 - The in operator in Python (for list, string, dictionary, etc.) def my_find(l, x): if x in l: return l.index(x) else: return -1 l = [30, 50, 10, 40, 20] print(my_find(l, 30)) # 0 print(my_find(l, 100)) # -1
🌐
iO Flood
ioflood.com › blog › python-get-index-of-item-in-list
Python Get Index of Item In List | 3 Simple Methods
June 29, 2024 - Python list indices start from 0, so ‘apple’ is at index 0, ‘banana’ at index 1, and ‘cherry’ at index 2. The list.index() function takes one mandatory argument, which is the item you’re looking for.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-find-the-index-for-a-given-item-in-a-python-list
How to Find Index of Item in Python List - GeeksforGeeks
July 23, 2025 - If we want to find the index of an item while iterating over the list, we can use enumerate() function. This is helpful when we are searching for an item during iteration. ... a = [10, 20, 30, 40, 50] # `i` is the index, `val` is the value at ...
🌐
Iditect
iditect.com › faq › python › get-index-in-the-list-of-objects-by-attribute-in-python.html
Get index in the list of objects by attribute in Python
class MyClass: def __init__(self, ... find object index in list by attribute value" Description: This query aims to locate the index of an object within a list by matching a specific attribute value in Python....
🌐
GeeksforGeeks
geeksforgeeks.org › python › get-index-in-the-list-of-objects-by-attribute-in-python
Get index in the list of objects by attribute in Python - GeeksforGeeks
July 23, 2025 - We have an if condition inside our for loop that says if the val attribute of item x from the list has the same value as the target value, then return its index value. The enumerate function provides these index values. Now let's look at how it works. we've defined a list, for example, within variable li, and we are going to convert this list of integer values into a list of objects.
🌐
Flexiple
flexiple.com › python › find-index-of-element-in-list-python
Find index of element in list Python | Flexiple Tutorials | Python - Flexiple
March 10, 2022 - This may seem easy when dealing with a small list; however, this could become tedious when the length of the list increases. To facilitate this, Python has an inbuilt function called index(). This function takes in the element as an argument and returns the index. By using this function we are able to find the index of an element in a list in Python.
🌐
Python Engineer
python-engineer.com › posts › find-index-of-item-in-list
How to find the index of an item in a List in Python - Python Engineer
my_list = ["apple", "apple", "cherry"] my_list.index("apple") # --> 0 idxs = [i for (i, e) in enumerate(my_list) if e == "apple"] # [0, 1] You can learn more about list comprehension here, and more about enumeration here. ... 🚀 Solve 42 programming puzzles over the course of 21 days: Link* * These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project.
🌐
freeCodeCamp
freecodecamp.org › news › python-index-find-index-of-element-in-list
Python Index – How to Find the Index of an Element in a List
May 2, 2022 - Each item in programming_languages list is also a list. The in operator then checks whether "Python" is present in this list or not. If present, we store the sublist index and index of "Python" inside the sublist as a tuple. The output is a list of tuples.
🌐
datagy
datagy.io › home › python posts › python lists › python: find list index of all occurrences of an element
Python: Find List Index of All Occurrences of an Element • datagy
December 30, 2022 - 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 ...
🌐
ReqBin
reqbin.com › code › python › h54arbqc › python-list-index-example
How do I find the index of an element in a Python list?
A Python list is mutable, which means that it can be changed by adding or removing elements or by sorting. The list size is not fixed and changes every time you add or remove items to/from the list. ... my_list = ["maths", "physics", "informatics", "chemistry"] print(my_list.index("informatics")) # output: 2