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.

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
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 no .get(idx[, default]) on python list??
There was a lengthy thread on this on Python-Ideas a couple of years ago: https://mail.python.org/archives/list/python-ideas@python.org/thread/LLK3EQ3QWNDB54SEBKJ4XEV4LXP5HVJS/ The clearest explanation of the most common objection was from Marc-Andre Lemburg: dict.get() was added since the lookup is expensive and you want to avoid having to do this twice in the common case where the element does exist. It was not added as a way to hide away an exception, but instead to bypass having to generate this exception in the first place. dict.setdefault() has a similar motivation. list.get() merely safes you a line of code (or perhaps a few more depending on how you format things), hiding away an exception in case the requested index does not exist. If that's all you want, you're better off writing a helper which hides the exception for you. I argue that making it explicit that you're expecting two (or more) different list lengths in your code results in more intuitive and maintainable code, rather than catching IndexErrors (regardless of whether you hide them in a method, a helper, or handle them directly). So this is more than just style, it's about clarity of intent. More on reddit.com
🌐 r/Python
94
144
June 23, 2022
Best way to handle list.index(might-not-exist) in python? - Stack Overflow
I have code which looks something like this: thing_index = thing_list.index(thing) otherfunction(thing_list, thing_index) ok so that's simplified but you get the idea. Now thing might not actually... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 ...
🌐
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.

🌐
Learn By Example
learnbyexample.org › python-list-index-method
Python List index() Method - Learn By Example
December 22, 2022 - L = ['a','b','c','d','e','f','... 'c' is not in list · To avoid such exception, you can check if item exists in a list, using in operator inside if statement....
🌐
DEV Community
dev.to › kiani0x01 › python-get-index-of-item-in-list-4pgk
Python Get Index of Item in List - DEV Community
August 6, 2025 - If you anticipate fewer misses, catching exceptions is often faster. What if your list has duplicates and you need every index? Python’s index() won’t cut it. You can use a loop or list comprehension: colors = ['red', 'blue', 'red', 'green', 'red'] all_positions = [i for i, c in enumerate(colors) if c == 'red'] print(all_positions) # [0, 2, 4] ... def find_all(lst, val): positions = [] for i, item in enumerate(lst): if item == val: positions.append(i) return positions print(find_all(colors, 'red')) # [0, 2, 4]
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-list-index
Python List index() - Find Index of Item - GeeksforGeeks
index() method in Python is a helpful tool when you want to find the position of a specific item in a list. It works by searching through the list from the beginning and returning the index (position) of the first occurrence of the element you're ...
Published   April 27, 2025
Find elsewhere
🌐
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 we don't want to spend time checking if an item exists in the list or not, especially for large lists, we can handle the ValueError like this: books = ["Cracking the Coding Interview", "Clean Code", "The Pragmatic Programmer"] try: ind = books.index("Design Patterns") except ValueError: ind = -1 ind
🌐
ReqBin
reqbin.com › code › python › h54arbqc › python-list-index-example
How do I find the index of an element in a Python list?
Unlike the list.index() method, the "in" operator does not return the element's index and does not throw an exception. Find the Element in the Python List using in Operator · my_list = ['Opera', 'Chrome', 'Firefox', 'Safari'] if 'Chrome' in ...
🌐
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
try: idx = my_list.index("orange") except ValueError: idx = -1 · A call to index searches through the list until it finds a match, and stops there. If you expect to need indices of more matches, you could use a list comprehension or generator expression. 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.
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
🌐
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 - Using index() method is the simplest method to find index of list item. index() method returns the index of first occurrence of a specified value. If the item is not found, it raises a ValueError.
🌐
Milddev
milddev.com › python-get-index-of-item-in-list
Python Get Index of Item in List
A quick in check has O(n) cost, then index() is another O(n). If you anticipate fewer misses, catching exceptions is often faster. What if your list has duplicates and you need every index? Python’s index() won’t cut it. You can use a loop or list comprehension: ... Data cleaning: mark all invalid entries. Analytics: track all occurrences. GUI lists: highlight every match. These patterns give you full control without external libraries.
🌐
Reddit
reddit.com › r/python › why no .get(idx[, default]) on python list??
r/Python on Reddit: Why no .get(idx[, default]) on python list??
June 23, 2022 -

Hi all,

today it happened once again that I could really use a .get(idx[, default]) method on python lists. Here is a brief example why it could be useful (I know there are many alternative solutions to this specific problem here, so please focus generally on the idea of .get for lists).

file_name = 'test.png'
if '.' in file_name:
    extension = file_name.rsplit('.', maxsplit=1)[1]
else:
    extension = ''

If we had such a method we could make the code much more concise

file_name = 'test.png'
extension = file_name.rsplit('.', maxsplit=1).get(1, '')

I wonder why this useful method does not exist, especially since it is available for dicts.

dd = {'a': 'AAA'}
print(f"{dd['a']}; {dd.get('a')}; {dd.get('c')}; {dd.get('c', 'nothing here')}; ")
# AAA; AAA; None; nothing here;

Thoughts / ideas why this is not present? Are there valid reasons not to have this method? Is it not available because someone has to invest the work to code it? How could something like this be initiated? :)

Top answer
1 of 23
155
There was a lengthy thread on this on Python-Ideas a couple of years ago: https://mail.python.org/archives/list/python-ideas@python.org/thread/LLK3EQ3QWNDB54SEBKJ4XEV4LXP5HVJS/ The clearest explanation of the most common objection was from Marc-Andre Lemburg: dict.get() was added since the lookup is expensive and you want to avoid having to do this twice in the common case where the element does exist. It was not added as a way to hide away an exception, but instead to bypass having to generate this exception in the first place. dict.setdefault() has a similar motivation. list.get() merely safes you a line of code (or perhaps a few more depending on how you format things), hiding away an exception in case the requested index does not exist. If that's all you want, you're better off writing a helper which hides the exception for you. I argue that making it explicit that you're expecting two (or more) different list lengths in your code results in more intuitive and maintainable code, rather than catching IndexErrors (regardless of whether you hide them in a method, a helper, or handle them directly). So this is more than just style, it's about clarity of intent.
2 of 23
25
In any case it would have ever been helpful for me, there's a better way to do what I was trying to do. In your case you can use os module which I'd argue is a bit more idiomatic. os.path.splitext(file_name)[1].lstrip('.') Or since if I have file paths I ususally like to work with pathlib: Path(file_name).suffix.lstrip('.') Either case makes it very clear what is happening
🌐
Python Examples
pythonexamples.org › python-find-index-of-item-in-list
How to find index of an item in a list?
We shall demonstrate this using ... in list") ... In this Python Tutorial, we learned how to find the index of an element/item in a list using list.index() method, with the help of well detailed examples....
🌐
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 - Master Python's index() function to efficiently locate items in lists, handle errors with custom functions, and improve data analysis using advanced techniques.
🌐
DEV Community
dev.to › kiani0x01 › find-index-of-item-in-python-list-541o
Find Index of Item in Python List - DEV Community
July 22, 2025 - The good news is that Python provides multiple ways to locate an element’s position—or handle it gracefully when the item isn’t found. Understanding these approaches can save you from runtime surprises and help you write more robust code. The simplest way to find the first occurrence of an item is the built-in list method: fruits = ['apple', 'banana', 'cherry', 'date'] idx = fruits.index('cherry') print(idx) # Output: 2
🌐
CodeRivers
coderivers.org › blog › find-index-of-item-in-list-python
Finding the Index of an Item in a Python List - CodeRivers
February 22, 2026 - As mentioned earlier, when using the index() method, it's important to handle the ValueError that may occur if the item is not in the list. This can be done using a try - except block as shown in the previous example. When using loops, it's also a good practice to handle the case where the ...