-4

I am on python 3.7.1.

I am working with data structures, and when using lists, I ran into a bug. When I try to access index -1, python gives me the last entry in the list.

I opened python shell, and ran the following commands:

>>> l = [0,1,2]
>>> l[-1]
2
>>> l[3]
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    l[3]
IndexError: list index out of range

This is probably due to a bug on python 3.7.1, but is there a way other than updating python that fixes this? I'm in the middle of a project.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
PythonPro
  • 291
  • 2
  • 11

2 Answers2

6

Negative indices mean you're counting from the right, not the left. so l[-1] accesses the last index in the array, l[-2] access the second to last, etc.

l[3] doesn't work because you have indices of 0, 1, and 2, there is no 3.

Shep
  • 166
  • 3
3

You have the list: l = [0,1,2] the length of the list is 3, you have 3 items but the indexes start in 0, so:

l [0] = 0

l [1] = 1

l [2] = 2

l[3] is out of range since the list goes from 0 to 2

When you use negative indexes you move from the right.

l [-2] = 1

Alexis
  • 117
  • 2
  • 7