a = [1]
try:
    index_value = a.index(44)
except ValueError:
    index_value = -1

How about this?

Answer from Jakob Bowyer on Stack Overflow
Top answer
1 of 6
44
a = [1]
try:
    index_value = a.index(44)
except ValueError:
    index_value = -1

How about this?

2 of 6
18

I agree with the general solution that was pointed out, but I'd like to look a bit more into the approaches that were explained in the answers and comments to see which one is more efficient and in which situations.

First of all, the three basic approaches:

>>> def my_index(L, obj):
...     for i, el in enumerate(L):
...             if el == obj:
...                     return i
...     return -1
... 
>>> def my_index2(L, obj):
...     try:
...             return L.index(obj)
...     except ValueError:
...             return -1
... 
>>> def my_index3(L, obj):
...     if obj in L:
...             return L.index(obj)
...     return -1
... 

The first and second solutions scan the list only once, and so you may think that they are faster than the third one because it scans the list twice. So let's see:

>>> timeit.timeit('my_index(L, 24999)', 'from __main__ import my_index, L', number=1000)
1.6892211437225342
>>> timeit.timeit('my_index2(L, 24999)', 'from __main__ import my_index2, L', number=1000)
0.403195858001709
>>> timeit.timeit('my_index3(L, 24999)', 'from __main__ import my_index3, L', number=1000)
0.7741198539733887

Well the second is really the fastest, but you can notice that the first one is much slower than the third one, even though it scans the list only once. If we increase the size of the list things does not change much:

>>> L = list(range(2500000))
>>> timeit.timeit('my_index(L, 2499999)', 'from __main__ import my_index, L', number=100)
17.323430061340332
>>> timeit.timeit('my_index2(L, 2499999)', 'from __main__ import my_index2, L', number=100)
4.213982820510864
>>> timeit.timeit('my_index3(L, 2499999)', 'from __main__ import my_index3, L', number=100)
8.406487941741943

The first one is still 2x times slower.

and if we search something that it's not in the list things get even worse for the first solution:

>>> timeit.timeit('my_index(L, None)', 'from __main__ import my_index, L', number=100)
19.055058002471924
>>> timeit.timeit('my_index2(L, None)', 'from __main__ import my_index2, L', number=100)
5.785136938095093
>>> timeit.timeit('my_index3(L, None)', 'from __main__ import my_index3, L', number=100)
5.46164608001709

As you can see in this case the third solution beats even the second one, and both are almost 4x faster than the python code. Depending on how often you expect the search to fail you want to choose #2 or #3(even though in 99% of the cases number #2 is better).

As a general rule, if you want to optimize something for CPython then you want to do as much iterations "at C level" as you can. In your example iterating using a for loop is exactly something you do not want to do.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-list-index
Python List index() - Find Index of Item - GeeksforGeeks
Explanation: a.index("dog") searches for "dog" in the list and element is found at index 1, so 1 is returned.
Published: July 17, 2026
Discussions

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
Find the index of a list element in Python - Stack Overflow
How could I find a certain index as to where one of the elements is located at within sets. So I would like to find where (2.0, 2.0, 152) is located within the sets list, which is the 5th index. Is... More on stackoverflow.com
🌐 stackoverflow.com
python - How can I find the index for a given item in a list? - Stack Overflow
Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index 1? More on stackoverflow.com
🌐 stackoverflow.com
Why doesn't this work? (List index in if statement)
[:3] gives you a slice of the elements from 0 to 3: >>> myList[:3] ('one', 'one', 'one') So no, it is not equal to "one". To get a specific element, use [3] - without the colon. More on reddit.com
🌐 r/learnpython
14
5
November 15, 2021
🌐
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 - For that, Python's built-in index() method is used as a search tool. ... .index() is the search method which takes three parameters. One parameter is required and the other two are optional. item is the required parameter.
🌐
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)
🌐
Reddit
reddit.com › r/learnpython › how to find the index of something in a list without knowing the full item
r/learnpython on Reddit: How to find the index of something in a list without knowing the full item
March 29, 2021 -

Hey everyone, I was wondering how I could find the index of an element without knowing the full element. For example, if I have the list of: [‘dog’, ‘cat’, ‘hamster’] and I don’t know what each of them are, but I know that one includes ‘ham’, how could I find the index? Thanks for any help.

🌐
ReqBin
reqbin.com › code › python › h54arbqc › python-list-index-example
How do I find the index of an element in a Python list?
To find the index of an element in a Python list, you can use the list.index(element, start, end) method. The list.index() method takes an element as an argument and returns the index of the first occurrence of the matching element.
🌐
FavTutor
favtutor.com › blogs › get-list-index-python
Get the Index of an Element in a List in Python | FavTutor
July 19, 2026 - In Python, you get the index of an element in a list with the index() method: my_list.index(value) returns the position of the first match.
Find elsewhere
🌐
DataCamp
datacamp.com › tutorial › python-list-index
Python List index() Method Explained with Examples | DataCamp
March 28, 2025 - Learn how to use Python's index() function to find the position of elements in lists. Includes examples, error handling, and tips for beginners.
🌐
Mimo
mimo.org › tutorials › python › how-to-find-index-of-element-in-list-in-python
How to Find Index of Element in List in Python
nums = [3, 8, 12, 7, 5] index_even = None for i, n in enumerate(nums): if n % 2 == 0: index_even = i break print(index_even) What to look for: break matters. Without it, you’ll end up with the last matching index, not the first.
🌐
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 - If it is Math then we store that index value in a list. We do this entire process using list comprehension, which is just syntactic sugar that allows us to iterate over a list and perform some operation. In our case we are doing decision making based on the value of list item. Then we create a new list. With this process, we now know all the shelf numbers which have math books on them. programming_languages = [["C","C++","Java"],["Python","Rust","R"],\ ["JavaScript","Prolog","Python"]] [ (i, x.index("Python")) for i, x in enumerate(programming_languages) if "Python" in x ]
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-handling-no-element-found-in-index
Handling " No Element Found in Index() " - Python - GeeksforGeeks
July 12, 2025 - Explanation: Try block tries to find the index of 11 in the list a. If 11 is not found, it catches the ValueError and assigns -1 to res. next() combined with a generator expression offers an elegant solution for finding the index of an element ...
🌐
Python Examples
pythonexamples.org › python-find-index-of-item-in-list
How to find index of an item in a list?
To find index of an item in a list, you can use list.index() method with the item passed as argument. In this tutorial, we will learn how to use list.index() method to find the index of specified element in this list, with well detailed examples.
🌐
Temp Mail
tempmail.us.com › temp mail › blog › python › locating an item's index in a python list
Locating an Item's Index in a Python List - Temp Mail
July 24, 2024 - The versatility and power of Python's list operations are highlighted by the usage of .index() for simple retrieval, try: and except for error handling, and loops for processing multiple items.
Top answer
1 of 16
6114
>>> ["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
726

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
🌐
W3Schools
w3schools.com › python › ref_list_index.asp
Python List index() Method
Python Examples Python Compiler ... Plan Python Interview Q&A Python Training ... The index() method returns the position at the first occurrence of the specified value....
🌐
Altcademy
altcademy.com › blog › how-to-find-index-of-element-in-list-python
How to find index of element in list Python - Altcademy.com
June 13, 2023 - For example, consider the following ... and most straightforward way to find the index of an element in a list is to use the built-in index() method....
🌐
Python Guides
pythonguides.com › get-index-of-element-in-python-list
Find Element Positions Using Python List Index Method
December 29, 2025 - # Defining a Python list of US Cities us_cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"] # Using the Python index method to find Chicago city_index = us_cities.index("Chicago") print(f"The index of Chicago in the Python list is: {city_index}") In Python, indexing starts at 0. So, “New York” is at index 0, and “Chicago” returns 2. One thing I learned early in my career is that the Python index() method is “fragile” if the element isn’t there.
🌐
Finxter
blog.finxter.com › home › learn python blog › python list find element
Python List Find Element – Be on the Right Side of Change
December 10, 2022 - The following example searches the string element 'Sergey' in the list my_list and returns the index of the first occurrence, i.e., 2. my_list = ['Alice', 'Bob', 'Sergey', 'Larry', 'Eric', 'Sundar'] # Element to be searched element = 'Sergey' # Search element in the list index = my_list.index(element) # Printing the index of the element print('Element found at index:', index)