Lỗi indexerror list index out of range trong python năm 2024

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.

Consider the list below:

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

In the example above, we have a list called

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

0. The list has three items — 'Python', 'JavaScript', and 'Java'.

To access the second item, we used its index:

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

1. This printed out

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

2.

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.

Here's an example:

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 = ['Python', 'JavaScript', 'Java']
print[languages[3]]
# IndexError: list index out of range

4. 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

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

7 loop.

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

Chủ Đề