You can use a try-except.

a = [1,2,3]

try:
  print(a[4])
except IndexError:
  pass
Answer from user11115921 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-list-index-out-of-range-indexerror
How to Fix IndexError - List Index Out of Range in Python - GeeksforGeeks
July 1, 2026 - Use valid positive and negative indexes. Prefer enumerate() when iterating through lists. Use try-except blocks when index values may be uncertain. Avoid using ranges that exceed the list size.
Discussions

"IndexError: list index out of range" not sure how to fix
I believe it is because you are deleting a value in your array while you’re in the middle of iterating through it. If you’re looping through with an original length of 5 and you delete one the new length is now 4 but you are still attempting to loop over the original 5 which is why you’re getting an index error. It looks like you are trying to remove duplicates from an array. The better way to do this would be to add each element to a new array only if it is not already in the new array. An even better way would be to use a set. More on reddit.com
🌐 r/learnpython
13
3
January 4, 2023
I keep getting “IndexError: list index out of range” when trying to run my code. What should I do?
This is most likely a problem on your side regarding logic inside the code. That error occurs when you try to access an element of a list with an index that exceeds the length of the list. For example, if you have a list = [A, B, C, D] and you say list[10], python won't have an idea of what to do, because there are only 4 elements in the list. If you are 100% sure that you did not make any mistakes (please check), this might be a manim bug and should be reported including all error logs and steps to reproduce. More on reddit.com
🌐 r/manim
21
6
January 31, 2021
String Index out of range error in while loop
Hey guys, I'm just getting into this, so please forgive me. I am working through the MIT class set to learn Python and keep getting an out of range error when trying to iterate through a character string by character. More on reddit.com
🌐 r/learnpython
17
1
September 7, 2016
Newbie Issue: "IndexError: list index out of range"
The place variable is set to 0 before the first iteration of the while loop, and inside the for loop it is increased by one for every element in nene, do you see why? Then, on the next go through the while loop, the place variable is not reset, and is already larger than the length of the nene array, so doing nene[place][0] will give you an index error. More on reddit.com
🌐 r/learnpython
4
1
May 5, 2020
People also ask

What causes list index out of range in Python?
It occurs when code requests an index outside the list's valid zero-based positions, including on an empty list.
🌐
pythonpool.com
pythonpool.com › home › tutorials › python list index out of range: fixes and examples
Python List Index Out Of Range: Error and Resolution
How do you fix list index out of range in Python?
There is no single fix; the right approach depends on what your code is doing. If you are looping to access each element, iterate directly over the list with for item in test_list, which removes indices entirely. If you need a specific index and aren't sure the list is long enough, guard the access with a length check, and use range(len(test_list)) when you need index-based loops.
🌐
rollbar.com
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
What causes "IndexError: list index out of range" in Python?
The error means you tried to access a position in a list that doesn't exist. Python lists are zero-indexed, so a list with 4 elements has valid indices 0, 1, 2, and 3, and accessing index 4 is one past the end. The most frequent causes are off-by-one errors in loops, hardcoded indices that assume a certain list length, calling an index on an empty list, and dynamic data such as user input, file contents, or database results where the list length varies.
🌐
rollbar.com
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
🌐
Rollbar
rollbar.com › home › how to fix python’s “list index out of range” error in for loops
How to Fix Python’s “List Index Out of Range” Error in For Loops
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
🌐
LearnPython.com
learnpython.com › blog › list-index-out-of-range
How to Fix the “List index out of range” Error in Python | LearnPython.com
June 26, 2023 - There are other ways to do error handling in Python that will help you avoid errors like “list index out of range”. For example, you could implement a try-exceptaa block instead of the if-else statement.
🌐
freeCodeCamp
freecodecamp.org › news › list-index-out-of-range-python-error-message-solved
List Index Out of Range – Python Error Message Solved
January 20, 2022 - You can also use negative indexing to access items inside lists in Python. To access the last item, you use the index value of -1. To acces the second to last item, you use the index value of -2. Here is how you would access each item inside ...
🌐
Flexiple
flexiple.com › python › list-index-out-of-range-python
List Index Out of Range – Python Error [Solved] - Flexiple - Flexiple
March 10, 2022 - Use loops that respect the list's boundaries, and always verify the list's length before accessing it by index. This careful approach prevents attempts to access non-existent indices, thus avoiding the list index out of range error.
🌐
Codegive
codegive.com › blog › list_index_out_of_range.php
Mastering 'list index out of range' Errors (2026 Edition): Unlock Robust Python Code
Avoid common pitfalls: Watch out for off-by-one errors, modifying lists during iteration, and assuming non-empty lists. Mastering these techniques ensures more stable, maintainable, and professional Python code, directly addressing and preventing the common 'list index out of range' problem.
Find elsewhere
🌐
Python Pool
pythonpool.com › home › tutorials › python list index out of range: fixes and examples
Python List Index Out Of Range: Error and Resolution
July 13, 2026 - Prefer for item in items when you do not need an index, and use enumerate(items) when you need both the index and the value. The official IndexError documentation describes this exception as a sequence subscript being out of range.
🌐
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
This error means you tried to access a position in a list that doesn't exist. Python lists are zero-indexed, meaning the first element is at index 0, the second is at index 1, and so on.
Published: 2 weeks ago
🌐
Opensource.com
opensource.com › article › 23 › 1 › fix-indexerror-python
How to fix an IndexError in Python | Opensource.com
January 19, 2023 - The only solution to fix the IndexError: list index out of range error is to ensure that the item you access from a list is within the range of the list.
🌐
OneUptime
oneuptime.com › home › blog › how to fix 'indexerror: list index out of range' in python
How to Fix 'IndexError: list index out of range' in Python
January 25, 2026 - # Slicing never raises IndexError items = [1, 2, 3] print(items[0:10]) # [1, 2, 3] (no error!) print(items[10:20]) # [] (empty, no error!) # Use slice to safely get first/last N items def first_n(lst, n): return lst[:n] def last_n(lst, n): return lst[-n:] if n > 0 else [] print(first_n([1, 2, 3], 10)) # [1, 2, 3] print(last_n([1, 2, 3], 10)) # [1, 2, 3] def bounded_index(lst, index): """Clamp index to valid range.""" if not lst: return None index = max(0, min(index, len(lst) - 1)) return lst[index] items = [1, 2, 3] print(bounded_index(items, -10)) # 1 (clamped to 0) print(bounded_index(items, 100)) # 3 (clamped to last)
🌐
Reddit
reddit.com › r/learnpython › "indexerror: list index out of range" not sure how to fix
r/learnpython on Reddit: "IndexError: list index out of range" not sure how to fix
January 4, 2023 -

I'm wondering how to format my "for loop" so it applies to any list of numbers inputted and so I don't get this error: "IndexError: list index out of range" and also .

I'm having a hard time understanding when to use what in my loops (i.e. for x in range(value) vs for x in value), or when to use while loops, etc. Are there any detailed guides on this somewhere? i have 3 books and I've searched the internet, but haven't found anything that's both understandable and goes into greater detail.

Here is my code, it calculates what I want (New = 2, 3), but I get the error at the end and I'm not sure how to fix it.

values = [2, 2, 3, 3, 3]
numbers = values.copy()

for x in range(len(numbers)):
        while numbers[x] == numbers[x-1]:
            del numbers[x]   
            print(f"Original = {values}")
            print(f"New = {numbers}")


This is the output for my code:
Original = [2, 2, 3, 3, 3]
New = [2, 3, 3, 3]
Original = [2, 2, 3, 3, 3]
New = [2, 3, 3]
Original = [2, 2, 3, 3, 3]
New = [2, 3]
Traceback (most recent call last):

    while numbers[x] == numbers[x-1]:

IndexError: list index out of range
🌐
PyTutorial
pytutorial.com › fix-python-list-index-out-of-range-error
PyTutorial | Fix Python List Index Out of Range Error
March 28, 2026 - It teaches you about list boundaries and careful programming. The key is to remember that list indices start at 0 and end at length-1. To avoid it, check lengths, use direct loops, and handle potential errors.
🌐
LabEx
labex.io › tutorials › python-how-to-fix-indexerror-list-index-out-of-range-417491
How to fix IndexError: list index out of range | LabEx
Now that you understand the common ... The most straightforward way to avoid IndexError is to check the length of the list before attempting to access an element....
🌐
Scaler
scaler.com › home › topics › how to fix indexerror - list index out of range in python
How to Fix IndexError - list index out of range in Python | Scaler Topics
February 8, 2024 - ... A more Pythonic solution is to iterate directly over the list items, removing the need to use indices altogether. ... By iterating directly over the elements, you eliminate the risk of an IndexError because you're not manually handling the indices. List Index out of range error in Python ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-indexerror-list-assignment-index-out-of-range-solution
Python Indexerror: list assignment index out of range Solution - GeeksforGeeks
July 23, 2025 - Let’s explore how to handle the IndexError: list assignment index out of range in Python. To avoid indexerror, we can use append() to safely add elements to a list without worrying about exceeding the list's index range.
🌐
STechies
stechies.com › fix-list-index-out-range-python
Indexerror: list Index Out of Range in Python
0 Apple 1 Banana 2 Orange 3 Traceback ... list has indexed only up to 2. To avoid such type of error, we have to run for loop in the range of “list” length....
🌐
LearnDataSci
learndatasci.com › solutions › python-indexerror-list-index-out-range-and-python
IndexError: list index out of range and python – LearnDataSci
Once the for loop has finished iterating through all of the list values, we replace the old list. This index error is triggered when indexing a list using a value outside of its range of indexes. The best way to avoid it is by carefully considering what range of indexes a list might have, taking ...
🌐
Moon Technolabs
moontechnolabs.com › qanda › fix-indexerror-list-index-out-of-range-easily
How to Fix IndexError: List Index Out of Range Error Fast
March 18, 2025 - ✔ Check list length before accessing an index. ✔ Use if len(list) > index: to prevent errors. ✔ Avoid empty lists by verifying with if list:. ✔ Use try-except IndexError for handling dynamic lists.
🌐
CodeRivers
coderivers.org › blog › python-list-index-out-of-range
Understanding and Handling `Python List Index Out of Range` - CodeRivers
February 22, 2026 - For example, when iterating over a list, you can use range(len(my_list)) to avoid going out of range. my_list = [5, 10, 15] for i in range(len(my_list)): print(my_list[i]) The IndexError: list index out of range is a common error in Python when working with lists.