-1

I was trying to use list slices earlier in python, and came across a strange case where I was expecting a particular list slice to cause an error.

Take for instance a list, a, with the following elements.

>>> a = [1,2,3,4]
>>> a[0:4]
>>> [1,2,3,4]

Furthermore, using the correct index removes an element

>>> a[0:3]
>>> [1,2,3]

Can someone make this make sense please? This is making use of list slices quite confusing.

benj
  • 29
  • 3

1 Answers1

3

The second index is exclusive, meaning the last element the slice will return is the one in front of the specified index. Thus, in your example [0:4] returns elements in indices 0 to 3.

Filip Müller
  • 1,096
  • 5
  • 18