If you don't care where the matching element is, then use:

found = x in somelist

If you do care, then use a LBYL style with a conditional expression:

i = somelist.index(x) if x in somelist else None
Answer from Raymond Hettinger on Stack Overflow
🌐
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 ...
Discussions

Python index of item in list without error? - Stack Overflow
It's still a lot faster than iterating over the list from python.(Obviously it would be even faster to call index and handle the error) ... @Junuxx I've clarified that in an answer, so that the OP can see himself the difference between his approach, the solutions already proposed and Gil's advice. ... Save this answer. ... Show activity on this post. Copya = [1] try: index_value = a.index(44) except ... More on stackoverflow.com
🌐 stackoverflow.com
How to tell python to ignore 'list out of index range' error?
You should update your win checker, not just suppress errors. I'd recommend making 3 sub-funcitons: check_win_vertical, check_win_horizontal, and check_win_diagonal. Then in each of those you can set up your iteration so that you don't have issues. More on reddit.com
🌐 r/learnpython
7
1
February 15, 2022
indexing - Python list.index throws exception when index not found - Stack Overflow
Is an item not appearing in a list an exceptional situation tho? 2022-05-05T13:41:38.613Z+00:00 ... Well, the special value would actually have to be None, because -1 is a valid index (meaning the last element of a list). ... It does seem at times that Python has been written so you write as ... More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
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
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.

🌐
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....
🌐
Rollbar
rollbar.com › home › how to fix python’s “list index out of range” error in for loops
Fix Python List Index Out of Range Error | Rollbar
Fix Python's list index out of range error in for loops with enumerate(), length checks, or -1 to safely access the last item.
Published: June 30, 2026
🌐
TutorialsPoint
tutorialspoint.com › how-to-catch-indexerror-exception-in-python
How to catch IndexError Exception in Python?
In this example, we try to access a sublist index that doesn't exist in the list, which will cause an error - matrix = [[1, 2], [3, 4]] try: print(matrix[2][0]) except IndexError: print("IndexError caught in nested list.")
Find elsewhere
🌐
Finxter
blog.finxter.com › home › learn python blog › python list index() – a simple illustrated guide
Python List index() - A Simple Illustrated Guide - Be on the Right Side of Change
June 19, 2021 - The function ind finds all occurrences of a given value in a given list in linear runtime without throwing an error. Instead, it’ll simply return an empty list. ... The Python list.index(value) method throws a ValueError if the value is not ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-list-index-out-of-range-indexerror
How to Fix IndexError - List Index Out of Range in Python - GeeksforGeeks
November 19, 2024 - Since lists are dynamically sized and zero-indexed, it's important to ensure the index exists within the list's range before modifying it. Under · 2 min read Python List index() - Find Index of Item
🌐
Opensource.com
opensource.com › article › 23 › 1 › fix-indexerror-python
How to fix an IndexError in Python | Opensource.com
January 19, 2023 - The ultimate cause of IndexError is an attempt to access an item that doesn't exist within a data structure. Using the range() and len() functions is one solution, and of course keep in mind that Python starts counting at 0, not 1.
🌐
Reddit
reddit.com › r/learnpython › how to tell python to ignore 'list out of index range' error?
r/learnpython on Reddit: How to tell python to ignore 'list out of index range' error?
February 15, 2022 -

I'm trying to write a function that check the win condition in tic tac toe board:

win=False
def wincheck(marker,board):
    global win
    for index,items in enumerate(board):
        if board[index] == marker and board[index+1] == marker and board[index+2] == marker:
            win=True
            break
        if board[index] == marker and board[index+3] == marker and board[index+6] == marker:
            win=True
            break
        if board[index] == marker and board[index+4] == marker and board[index+8] == marker:
            win=True
            break
    return win

For my board of 1-9:

originalboard =[1,2,3,4,5,6,7,8,9]
def board_display(board):
    print("_" *6)
    for row in range(3):
        print("".join((f"|{board[row*3+ position]}" for position in range(3))) + "|")
        print("_" *6)

The problem is the wincheck function will return list out of index range error because index + 8 for index =2 for example is out of my table range and I don't want to widen my table list because it will screw up the board_display function

🌐
Rollbar
rollbar.com › home › how to fix indexerror: list index out of range in python
How to Fix IndexError: List Index Out of Range in Python
The IndexError: list index out of range almost always comes down to one thing: your code assumes the list has more elements than it actually does. The fix is to make sure you're never reaching past the end. Whether that means iterating directly, checking lengths, or catching exceptions depends on your specific situation - but now you have all the tools to handle it.
Published: 2 weeks ago
🌐
Stack Overflow
stackoverflow.com › questions › 2132718 › best-way-to-handle-list-indexmight-not-exist-in-python
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...
🌐
PythonForBeginners.com
pythonforbeginners.com › home › indexerror in python
IndexError in Python - PythonForBeginners.com
December 28, 2022 - The Tuple is: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Index is: 10 Index should be smaller. Alternatively, we can use python try except blocks to handle the IndexError exception after the program raises it.
🌐
Real Python
realpython.com › ref › builtin-exceptions › indexerror
IndexError | Python’s Built-in Exceptions – Real Python
>>> colors = [ ... "red", ... "green", ... "blue", ... ] >>> try: ... colors[10] ... except IndexError: ... print("The index is out of range.") ... The index is out of range. ... In this tutorial, you'll dive deep into Python's lists. You'll learn how to create them, update their content, populate and grow them, and more.
🌐
Medium
medium.com › @python-javascript-php-html-css › python-list-index-out-of-range-recognizing-the-problem-even-when-indexes-are-checked-a0cd7d7a0680
Python List Index Out of Range: Recognizing the Problem Even When Indexes Are Checked
November 14, 2024 - Use a copy or filtered list with enumerate() for safe tracking of index and values. What are best practices for working with lists in Python? Use try-except blocks for error handling, enumerate() for indexed loops, and list comprehensions for ...
🌐
W3Schools
w3schools.com › python › ref_exception_indexerror.asp
Python IndexError Exception
Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The IndexError exception occurs when you use an index on a sequence, like a list or a tuple, and the index is out of range.