Python index out exception

List Index Out of Range – Python Error [Solved]

Ihechikara Vincent Abba

Ihechikara Vincent Abba

List Index Out of Range – Python Error [Solved]

In this article, we’ll talk about the IndexError: list index out of range error in Python.

In each section of the article, I’ll highlight a possible cause for the error and how to fix it.

You may get the IndexError: list index out of range error for the following reasons:

  • Trying to access an index that doesn’t exist in a list.
  • Using invalid indexes in your loops.
  • Specifying a range that exceeds the indexes in a list when using the range() function.

Before we proceed to fixing the error, let’s discuss how indexing work in Python lists. You can skip the next section if you already know how indexing works.

How Does Indexing Work in Python Lists?

Each item in a Python list can be assessed using its index number. The first item in a list has an index of zero.

languages = ['Python', 'JavaScript', 'Java'] print(languages[1]) # JavaScript

In the example above, we have a list called languages . The list has three items — ‘Python’, ‘JavaScript’, and ‘Java’.

To access the second item, we used its index: languages[1] . This printed out JavaScript .

Some beginners might misunderstand this. They may assume that since the index is 1, it should be the first item.

To make it easier to understand, here’s a breakdown of the items in the list according to their indexes:

Python (item 1) => Index 0
JavaScript (item 2) => Index 1
Java (item 3) => Index 2

As you can see above, the first item has an index of 0 (because Python is «zero-indexed»). To access items in a list, you make use of their indexes.

What Will Happen If You Try to Use an Index That Is Out of Range in a Python List?

If you try to access an item in a list using an index that is out of range, you’ll get the IndexError: list index out of range error.

languages = ['Python', 'JavaScript', 'Java'] print(languages[3]) # IndexError: list index out of range

In the example above, we tried to access a fourth item using its index: languages[3] . We got the IndexError: list index out of range error because the list has no fourth item – it has only three items.

The easy fix is to always use an index that exists in a list when trying to access items in the list.

How to Fix the IndexError: list index out of range Error in Python Loops

Loops work with conditions. So, until a certain condition is met, they’ll keep running.

In the example below, we’ll try to print all the items in a list using a while loop.

languages = ['Python', 'JavaScript', 'Java'] i = 0 while i 

The code above returns the IndexError: list index out of range error. Let's break down the code to understand why this happened.

First, we initialized a variable i and gave it a value of 0: i = 0 .

We then gave a condition for a while loop (this is what causes the error): while i

From the condition given, we're saying, "this loop should keep running as long as i is less than or equal to the length of the language list".

The len() function returns the length of the list. In our case, 3 will be returned. So the condition will be this: while i

Let's pretend to be the Python compiler. Here's what happens as the loop runs.

Here's the list: languages = ['Python', 'JavaScript', 'Java'] . It has three indexes — 0, 1, and 2.

When i is 3 => Index not found in the list. IndexError: list index out of range error thrown.

So the error is thrown when i is equal to 3 because there is no item with an index of 3 in the list.

To fix this problem, we can modify the condition of the loop by removing the equal to sign. This will stop the loop once it gets to the last index.

languages = ['Python', 'JavaScript', 'Java'] i = 0 while i < len(languages): print(languages[i]) i += 1 # Python # JavaScript # Java 

The condition now looks like this: while i < 3 .

The loop will stop at 2 because the condition doesn't allow it to equate to the value returned by the len() function.

How to Fix the IndexError: list index out of range Error in When Using the range() Function in Python

By default, the range() function returns a "range" of specified numbers starting from zero.

Here's an example of the range() function in use:

for num in range(5): print(num) # 0 # 1 # 2 # 3 # 4

As you can see in the example above, range(5) returns 0, 1, 2, 3, 4.

You can use the range() function with a loop to print the items in a list.

The first example will show a code block that throws the IndexError: list index out of range error. After pointing out why the error occurred, we'll fix it.

languages = ['Python', 'JavaScript', 'Java'] for language in range(4): print(languages[language]) # Python # JavaScript # Java # Traceback (most recent call last): # File "", line 5, in # IndexError: list index out of range

The example above prints all the items in the list along with the IndexError: list index out of range error.

We got the error because range(4) returns 0, 1, 2, 3. Our list has no index with the value of 3.

To fix this, you can modify the parameter in the range() function. A better solution is to use the length of the list as the range() function's parameter.

languages = ['Python', 'JavaScript', 'Java'] for language in range(len(languages)): print(languages[language]) # Python # JavaScript # Java

The code above runs without any error because the len() function returns 3. Using that with range(3) returns 0, 1, 2 which matches the number of items in a list.

Summary

In this article, we talked about the IndexError: list index out of range error in Python.

This error generally occurs when we try to access an item in a list by using an index that doesn't exist within the list.

We saw some examples that showed how we may get the error when working with loops, the len() function, and the range() function.

We also saw how to fix the IndexError: list index out of range error for each case.

Источник

List Index Out of Range – Python Error Message Solved

Dionysia Lemonaki

Dionysia Lemonaki

List Index Out of Range – Python Error Message Solved

In this article you'll see a few of the reasons that cause the list index out of range Python error.

Besides knowing why this error occurs in the first place, you'll also learn some ways to avoid it.

How to Create a List in Python

To create a list object in Python, you need to:

  • Give the list a name,
  • Use the assignment operator, = ,
  • and include 0 or more list items inside square brackets, [] . Each list item needs to be separated by a comma.

For example, to create a list of names you would do the following:

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] 

The code above created a list called names that has four values: Kelly, Nelly, Jimmy, Lenny .

How to Check the Length of a List in Python

To check the length of a list in Python, use Python's build-in len() method.

len() will return an integer, which will be the number of items stored in the list.

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] #create a variable called name_length to store the length of the list name_length = len(names) #print value of variable to the console print(name_length) #output #4 

There are four items stored in the list, therefore the length of the list will be four.

How to Access Individual List Items in Python

Each item in a list has its own index number.

Indexing in Python, and most modern programming languages, starts at 0.

This means that the first item in a list has an index of 0, the second item has an index of 1, and so on.

You can use the index number to access the individual item.

To access an item in a list using its index number, first write the name of the list. Then, inside square brackets, include the intiger that corresponds with the item's index number.

Taking the example from earlier, this is how you would access each item inside the list using its index number:

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] names[0] # Kelly names[1] # Nelly names[2] # Jimmy names[3] # Lenny 

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 a list using negative indexing:

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] names[-4] # Kelly names[-3]# Nelly names[-2] # Jimmy names[-1] # Lenny 

Why does the Indexerror: list index out of range error occur in Python?

Using an index number that is out of the range of the list

You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist.

This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.

Let's go back to the list we've used so far.

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] 

Say I want to access the last item, "Lenny", and try to do so by using the following code:

print(names[4]) #output #Traceback (most recent call last): # File "/Users/dionysialemonaki/python_articles/demo.py", line 3, in # print(names[4]) #IndexError: list index out of range 

Generally, the index range of a list is 0 to n-1 , with n being the total number of values in the list.

With the total values of the list above being 4 , the index range is 0 to 3 .

Now, let's try to access an item using negative indexing.

Say I want to access the first item in the list, "Kelly", by using negative indexing.

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] print(names[-5]) #output #Traceback (most recent call last): # File "/Users/dionysialemonaki/python_articles/demo.py", line 3, in # print(names[-5]) #IndexError: list index out of range 

When using negative indexing, the index range of a list is -1 to -n , where -n the total number of items contained in the list.

With the total number of items in the list being 4 , the index range is -1 to -4 .

Using the wrong value in the range() function in a Python for loop

You'll get the Indexerror: list index out of range error when iterating through a list and trying to access an item that doesn't exist.

One common instance where this can occur is when you use the wrong integer in Python's range() function.

The range() function typically takes in one integer number, which indicates where the counting will stop.

For example, range(5) indicates that the counting will start from 0 and end at 4 .

So, by default, the counting starts at position 0 , is incremented by 1 each time, and the number is up to – but not including – the position where the counting will stop.

Let's take the following example:

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] for name in range(5): print(names[name]) #output #Kelly #Nelly #Jimmy #Lenny #Traceback (most recent call last): # File "/Users/dionysialemonaki/python_articles/demo.py", line 7, in # print(names[name]) #IndexError: list index out of range 

Here, the list names has four values.

I wanted to loop through the list and print out each value.

When I used range(5) I was telling the Python interpreter to print the values that are at the positions 0 to 4 .

However, there is no item in position 4.

You can see this by first printing out the number of the position and then the value at that position.

#0 #Kelly #1 #Nelly #2 #Jimmy #3 #Lenny #4 #Traceback (most recent call last): # File "/Users/dionysialemonaki/python_articles/demo.py", line 8, in # print(names[name]) #IndexError: list index out of range 

You see that at position 0 is "Kelly", at position 1 is "Nelly", at position 2 is "Jimmy" and at position 3 is "Lenny".

When it comes to position four, which was specified with range(5) which indicates positions of 0 to 4 , there is nothing to print out and therefore the interpreter throws an error.

One way to fix this is to lower the integer in range() :

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] for name in range(4): print(name) print(names[name]) #output #0 #Kelly #1 #Nelly #2 #Jimmy #3 #Lenny 

Another way to fix this when using a for loop is to pass the length of the list as an argument to the range() function. You do this by using the len() built-in Python function, as shown in an earlier section:

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] for name in range(len(names)): print(names[name]) #output #Kelly #Nelly #Jimmy #Lenny 

When passing len() as an argument to range() , make sure that you don't make the following mistake:

names = ["Kelly", "Nelly", "Jimmy", "Lenny"] for name in range(len(names) + 1): print(names[name]) 

After running the code, you'll again get an IndexError: list index out of range error:

#Kelly #Nelly #Jimmy #Lenny #Traceback (most recent call last): # File "/Users/dionysialemonaki/python_articles/demo.py", line 4, in # print(names[name]) #IndexError: list index out of range 

Conclusion

Hopefully this article gave you some insight into why the IndexError: list index out of range error occurs and some ways you can avoid it.

If you want to learn more about Python, check out freeCodeCamp's Python Certification. You'll start learning in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Источник

Читайте также:  Отправка get запроса python
Оцените статью