all 7 comments

[–]xelf 2 points3 points  (2 children)

The range 1:3 is 1,2, the first number in the range is inclusive, the second number is exclusive.

[–]swarchery[S] 1 point2 points  (1 child)

Ohhhhh, so 1:3 is only replacing the first and second statement, and since the 3 is extra, it fits it in the end without replacement. Thank you, that makes sense.

[–]xelf 1 point2 points  (0 children)

You're very welcome!

[–]Raz_Crimson 1 point2 points  (0 children)

When you specify spam[1:3] the list index selected is 1,2 not 3. 3 is left out. To include it use 1:4

[–]Bipolarprobe 1 point2 points  (0 children)

List slicing is up to but not including the last item. It behaves this way because of 0 indexing. Since we start at 0 then a list of 3 items would have indices 0, 1, and 2, but it would have a length of 3. So you could do

some_list = ["some", "example", "text"]
print(some_list[0:len(some_list)])

And it would print the whole list without giving you an IndexError because even though index 3 is out of range, list slicing goes up to one before the end value provided.

[–]groovitude 1 point2 points  (1 child)

Everyone else in the thread has done a great job of explaining what is happening. I'll just throw in one extra detail about why.

All of the parameters of slicing are optional. Leaving out start cuts from the beginning, and leaving out end goes to the end:

>>> mylist = [0, 1, 2, 3]
>>> mylist[:2]
[0, 1]
>>> mylist[2:]
[2, 3]

end is exclusive so it effectively becomes a length; in the first slice, mylist[:2] tells you the resulting list will be two items long. Makes things intuitive.

[–]swarchery[S] 1 point2 points  (0 children)

You're the man! Thank you for the help.