Indexerror list index out of range

권준태

Rock

질문 지켜보기를 시작하면 질문에 답변, 댓글이 달릴 때 알림을 받을 수 있어요.

This error occurs because the del command changes the list length while in the loop.

At the start of the for loop, the length of colors is five, so the range[] function generates the list [0, 1, 2, 3, 4].

Although our list length decreases every time we delete an item, the range list we are looping through will remain the same. We'll eventually run into the index error in the later stages of our for loop since range[] will be providing indexes greater than the length of the list.

To avoid editing the list directly while looping over it, we utilize list comprehension.

I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out?

0

파이썬에서 리스트를 만들고 실행 시 

Traceback [most recent call last]:
  File "C:/Users/MyRealm/PycharmProjects/untitled/ListExample.py", line 3, in      print[listVariable[5]] IndexError: list index out of range

Process finished with exit code 1

이런 에러가 뜨는 것이 보이는데

IndexError: list index out of range 에러는

list 범위 밖에 있는 인덱스를 가져오려고 해서 에러가 난 것이다

listVariable에는 9, 1, 3, 4가 들어있는데

리스트의 인덱스는 0부터 시작하기 때문에

0, 1, 2, 3까지 있는데

5번째 인덱스를 가져오라고 하니 에러가 난 것이다


If you are working with lists in Python, you have to know the index of the list elements. This will help you access them and perform operations on them such as printing them or looping through the elements. But in case you mention an index in your code that is outside the range of the list, you will encounter an IndexError.

List index out of range” error occurs in Python when we try to access an undefined element from the list.

The only way to avoid this error is to mention the indexes of list elements properly.

Example: 

# Declaring list list_fruits = ['apple', 'banana', 'orange'] # Print value of list at index 3 print[list_fruits[3]];

Output:

Traceback [most recent call last]:   File "list-index.py", line 2, in     print[list_fruits[3]]; IndexError: list index out of range

In the above example, we have created a list named “list_fruits” with three values apple, banana, and orange. Here we are trying to print the value at the index [3].

And we know that the index of a list starts from 0 that’s why in the list, the last index is 2, not 3

Due to which if we try to print the value at index [3] it will give an error.

Correct Example: 

# Declaring list list_fruits = ['Apple', 'Banana', 'Orange'] # Print list element at index 2 print[list_fruits[2]];

Output: 

Orange # Declaring list list_fruits = ['Apple', 'Banana', 'Orange'] i=0 # while loop less then and equal to list "list_fruits" length. while i Bob
  • lst[2] --> Carl
  • lst[3] --> ??? Error ???
  • Did you try to access the third element with index 3?

    It’s a common mistake: The index of the third element is 2 because the index of the first list element is 0.

    How to Fix the IndexError in a For Loop? [General Strategy]

    So, how can you fix the code? Python tells you in which line and on which list the error occurs.

    To pin down the exact problem, check the value of the index just before the error occurs.

    To achieve this, you can print the index that causes the error before you use it on the list. This way, you’ll have your wrong index in the shell right before the error message.

    Here’s an example of wrong code that will cause the error to appear:

    # WRONG CODE lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range[len[lst]+1]: lst[i] # Traceback [most recent call last]: # File "C:\Users\xcent\Desktop\code.py", line 5, in # lst[i] # IndexError: list index out of range

    The error message tells you that the error appears in line 5.

    So, let’s insert a print statement before that line:

    lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range[len[lst]+1]: print[i] lst[i]

    The result of this code snippet is still an error.

    But there’s more:

    0 1 2 3 4 Traceback [most recent call last]: File "C:\Users\xcent\Desktop\code.py", line 6, in lst[i] IndexError: list index out of range

    You can now see all indices used to retrieve an element.

    The final one is the index i=4 which points to the fifth element in the list [remember zero-based indexing: Python starts indexing at index 0!].

    But the list has only four elements, so you need to reduce the number of indices you’re iterating over.

    The correct code is, therefore:

    # CORRECT CODE lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range[len[lst]]: lst[i]

    Note that this is a minimal example and it doesn’t make a lot of sense. But the general debugging strategy remains even for advanced code projects:

    • Figure out the faulty index just before the error is thrown.
    • Eliminate the source of the faulty index.

    IndexError When Modifying a List as You Iterate Over It

    The IndexError also frequently occurs if you iterate over a list but you remove elements as you iterate over the list:

    l = [1, 2, 3, 0, 0, 1] for i in range[0, len[l]]: if l[i]==0: l.pop[i]

    This code snippet is from a StackOverflow question.

    The source is simply that the list.pop[] method removes the element with value 0.

    All subsequent elements now have a smaller index.

    But you iterate over all indices up to len[l]-1 = 6-1 = 5 and the index 5 does not exist in the list after removing elements in a previous iteration.

    You can fix this with a simple list comprehension statement that accomplishes the same thing:

    l = [x for x in l if x]

    Only non-zero elements are included in the list.

    String IndexError: List Index Out of Range

    The error can occur when accessing strings as well.

    Check out this example:

    s = 'Python' print[s[6]]

    Genius! Here’s what it looks like on my machine:

    To fix the error for strings, make sure that the index falls between the range 0 ... len[s]-1 [included]:

    s = 'Python' print[s[5]] # n

    Tuple IndexError: List Index Out of Range

    In fact, the IndexError can occur for all ordered collections where you can use indexing to retrieve certain elements.

    Thus, it also occurs when accessing tuple indices that do not exist:

    s = ['Alice', 'Bob'] print[s[2]]

    No. You didn’t? 😅

    Again, start counting with index 0 to get rid of this:

    s = ['Alice', 'Bob'] print[s[1]] # Bob

    Note: The index of the last element in any sequence is len[sequence]-1.

    Programmer Humor

    “Real programmers set the universal constants at the start such that the universe evolves to contain the disk with the data they want.” — xkcd

    Where to Go From Here?

    Enough theory. Let’s get some practice!

    Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

    To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

    You build high-value coding skills by working on practical coding projects!

    Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

    🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

    If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

    Join the free webinar now!

    While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

    To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

    His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

    Video liên quan

    Chủ Đề