How to fix – List Index Out of Range in Python
In this article, we are going to see how to fix – List Index Out of Range in Python
Why we get- List Index Out of Range in Python
The “list index out of your range” problem is likely something you’ve encountered if you’ve ever worked with lists. Even though this problem occurs frequently, it could be difficult for a new programmer to diagnose.
How to rise list index out of range:
Example 1:
Here our list is 3 and we are printing with size 4 so in this case, it will create a list index out of range
Python3
j = [ 1 , 2 , 4 ] print (j[ 4 ]) |
Output:
IndexError: list index out of range
Example 2:
Here we are printing the same pattern without of index.
Python3
# code names = [ "blue" , "red" , "green" ] for name in range ( len (names) + 1 ): print (names[name]) |
Output:
Traceback (most recent call last): File "/home/6536be743dacb18c2fcc724dd5aa21c6.py", line 5, in <module> print(names[name]) IndexError: list index out of range
How to solve list index out of range
- Using range()
- Using Closing thoughts
- Using Index()
Method 1: Using range()
The range is used to give a specific range, the Python range() function returns the sequence of the given number between the given range.
Syntax of range()
range(start, stop, step).
- start: An optional number that identifies the beginning of the series. 0 is the default value if it’s left blank.
- stop: An integer designating the point at which the sequence should end.
- step-: optional and needed if you want to increase the increment by more than 1. 1 is the default value.
The stop parameter for the range() function is the value returned by the len() function.
Example of fix list out of range error:
Python3
# code names = [ "blue," "red," "green" ] for name in range ( len (names)): print (names[name]) |
Output:
blue,red,green
Method 2: Using in operator
Python3
# code names = [ "blue," "red," "green" ] for i in names: print (i) |
Output:
blue,red,green
Method 3: Using Index()
Here we are going to create a list and then try to iterate the list using the constant values in for loops.
Python3
li = [ 1 , 2 , 3 , 4 , 5 ] for i in range ( 6 ): print (li[i]) |
Output:
1 2 3 4 5 IndexError: list index out of range
Reason of the error – The length of the list is 5 and if we are an iterating list on 6 then it will generate the error.
Solving this error without using len() or constant Value:
To solve this error we will take the index of the last value of the list and then add one then it will become the exact value of length.
Python3
li = [ 1 , 2 , 3 , 4 , 5 ] for i in range (li.index(li[ - 1 ]) + 1 ): print (li[i]) |
Output:
1 2 3 4 5
Please Login to comment...