IndexError: list index out of range and python

后端 未结 8 2256
醉酒成梦
醉酒成梦 2020-11-22 04:58

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?

相关标签:
8条回答
  • 2020-11-22 05:03

    The way Python indexing works is that it starts at 0, so the first number of your list would be [0]. You would have to print[52], as the starting index is 0 and therefore line 53 is [52].

    Subtract 1 from the value and you should be fine. :)

    0 讨论(0)
  • 2020-11-22 05:04

    That's right. 'list index out of range' most likely means you are referring to n-th element of the list, while the length of the list is smaller than n.

    0 讨论(0)
  • 2020-11-22 05:08

    If you read a list from text file, you may get the last empty line as a list element. You can get rid of it like this:

    list.pop()
    for i in list:
       i[12]=....
    
    0 讨论(0)
  • 2020-11-22 05:10

    If you have a list with 53 items, the last one is thelist[52] because indexing starts at 0.

    IndexError

    • Attribution to Real Python: Understanding the Python Traceback - IndexError

    The IndexError is raised when attempting to retrieve an index from a sequence (e.g. list, tuple), and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:

    Raised when a sequence subscript is out of range. (Source)

    Here’s an example that raises the IndexError:

    test = list(range(53))
    test[53]
    
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-6-7879607f7f36> in <module>
          1 test = list(range(53))
    ----> 2 test[53]
    
    IndexError: list index out of range
    

    The error message line for an IndexError doesn’t provide great information. See that there is a sequence reference that is out of range and what the type of the sequence is, a list in this case. That information, combined with the rest of the traceback, is usually enough to help quickly identify how to fix the issue.

    0 讨论(0)
  • 2020-11-22 05:10

    Yes. The sequence doesn't have the 54th item.

    0 讨论(0)
  • 2020-11-22 05:11

    Yes,

    You are trying to access an element of the list that does not exist.

    MyList = ["item1", "item2"]
    print MyList[0] # Will work
    print MyList[1] # Will Work
    print MyList[2] # Will crash.
    

    Have you got an off-by-one error?

    0 讨论(0)
提交回复
热议问题