List Slicing (last index minus 1)

Stupid bug caused because I didn’t remember this very simple fact! Suppose we have a list:

mylist = [1,2,3,4,5]

And we want to slice only the first two elements: [1,2].
Writing this:

print mylist[0:1]

will actually only give us this:

[1]

If we want to print the first two elements, we need to write

print mylist[0:2]

and then we get

[1,2]

because Python always selects the last index minus 1.

Advertisements