Python Forum
I hate "List index out of range"
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I hate "List index out of range"
#1
Thumbs Down 
Hello!

I have a question, but please don't give me the answer. I'm just looking for some tips. I'm new to Python, and I'm posting here because I can't understand the logic of the "index out of range" error. I know that in Python we count from 0, but I'm (almost) sure that I haven't made any mistakes, and it still doesn't work... Wall

Is there something I should know? I'm hesitant to post my program's code because I really want to figure it out on my own, but I need some help.


I would have liked to figure it out on my own without having to ask, but oh well...
Reply
#2
It could be many different errors you could make that result in an index out of range error, but they mostly fall into a few categories: You are not adding items to the list when you think you are. You are not indexing the list you think you are. Your counting is off.
Reply
#3
Besides the error, the traceback should also show you the variable that is causing the problem and the line number.

You can add some print statements on the line before to check what you are assuming. Let's say that I get the error like this:

Error:
Traceback (most recent call last): File "/tmp/indexerr.py", line 4, in <module> info = mylist[x] ~~~~~~^^^ IndexError: list index out of range
I might add some statements on line 3 that give me more information:

print(f"mylist has a length of {len(mylist)} and x has a value of {x}")
Now I can run the program and get more info:
Output:
mylist has a length of 15 and x has a value of 30 ...
Oh, no wonder I got an index error. Now I can track down why x is 30 here instead of whatever I expected it to be.
Gribouillis likes this post
Reply
#4
(May-09-2023, 09:44 PM)Melen Wrote: Hello!

I have a question, but please don't give me the answer. I'm just looking for some tips. I'm new to Python, and I'm posting here because I can't understand the logic of the "index out of range" error. I know that in Python we count from 0, but I'm (almost) sure that I haven't made any mistakes, and it still doesn't work... Wall

Is there something I should know? I'm hesitant to post my program's code because I really want to figure it out on my own, but I need some help.


I would have liked to figure it out on my own without having to ask, but oh well...

Thank you for your answer, I looked at all that but it does not seem to me to be that.
Reply
#5
Ok I guess I don't know how to respond properly to messages besides that!

deanhystad: Thanks for your answer, I looked and normally it shouldn't be one of those errors

bowlofred: Thank you!! I was doing this type of check before but not as accurate with a sentence like this comparing multiple variables. I test in all directions as I can and I come back to you :)
Reply
#6
A common mistake is to change a list over which one is iterating. Are you perhaps doing something like this?
mylist = ["one", "two", "three", "four"]
for i in range(len(mylist)):
    removed_item = mylist.pop(i)
    print(f"Removed item {removed_item}")
Output:
Removed item one Removed item three
Error:
Traceback (most recent call last): File "/home/ibreeden/PycharmProjects/Forum/forum02.py", line 3, in <module> removed_item = mylist.pop(i) IndexError: pop index out of range
Reply
#7
Melen Wrote:I hate "List index out of range"
Python's error tracebacks are the most useful things. They always tell you where the error comes from if you take the time to read them. In the glorious days of the C language, the error message in such cases was the infamous
Error:
Segmentation fault: core dumped
without any indication of what happened. You could spend weeks searching the mistake in your code.
ibreeden likes this post
Reply
#8
(May-09-2023, 09:44 PM)Melen Wrote: I can't understand the logic of the "index out of range" error

What specifically is beyond your understanding? If you count all items in object starting from zero and get 0, 1, 2 then what should happen if you are looking for item 4? To put it another way - if you have deck of 5 cards what should you say (or do) if somebody asks to give 6th card in the deck?

Slices can be out of range without raising error:

>>> s = 'abc'
>>> len(s)
3
>>> s[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[3:]
''
>>> s[100:120]
''
>>> l = [1, 2, 3]
>>> l[3:]
[]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#9
I think this discussion would be more fruitful if you would post your code. That would provide us with some insight about your blind spots.
Reply
#10
Indexing starts with 0.

The element at index 0 is the first
and at index -1 is the last element.

     
the list      :  [ "a", "b", "c", "d" ]
positive index:  [  0    1    2    3  ]
negative index:  [ -4   -3   -2   -1  ]
"a" is at index 0 and index -4
"b" is at index 1 and index -3
...

Accessing the list with an index, which does not exist, then it raises the IndexError.
This is also true for negative index which is out of range.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 6,410 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  IndexError: list index out of range dolac 4 1,924 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  I'm getting a String index out of range error debian77 7 2,361 Jun-26-2022, 09:50 AM
Last Post: deanhystad
  IndexError: list index out of range Anldra12 2 1,449 May-03-2022, 01:39 PM
Last Post: Anldra12
  TypeError: list indices must be integers or slices, not range Anldra12 2 2,591 Apr-22-2022, 10:56 AM
Last Post: Anldra12
  matplotlib x axis range goes over the set range Pedroski55 5 3,228 Nov-21-2021, 08:40 AM
Last Post: paul18fr
  IndexError: list index out of range rf_kartal 6 2,862 Sep-07-2021, 02:36 PM
Last Post: Larz60+
  Python Error List Index Out of Range abhi1vaishnav 3 2,325 Sep-03-2021, 08:40 PM
Last Post: abhi1vaishnav
  IndexError: list index out of range Laplace12 1 2,233 Jun-22-2021, 10:47 AM
Last Post: Yoriz
  IndexError: list index out of range brunolelli 11 6,576 Mar-25-2021, 11:36 PM
Last Post: brunolelli

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020