I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:
>>> s = 'spam' >>> s[:-1] 'spa'
Why does slicing with no beginning bound and a '-1' return every element except the last one? Is calling s[0:-1] logically the same as calling s[:-1]? They both return the same result. But I’m not sure what python is doing exactly. Any help would be greatly appreciated.
Yes, calling
s[0:-1]is exactly the same as callings[:-1].Using a negative number as an index in python returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side).
so if you have a list as so:
the print statement will print ‘e’.
Once you understand that (which you may already, it’s not entirely clear if that’s one of the things you’re confused about or not) we can start talking about slicing.
I’m going to assume you understand the basics of a slice along the lines of
myList[2:4](which will return['c', 'd']) and jump straight into the slicing notation where one side is left blank.As you suspected in your post,
myList[:index]is exactly the same asmyList[0:index].This is also works the other way around, by the way…
myList[index:]is the same asmyList[index:len(myList)]and will return a list of all the elements from the list starting atindexand going till the end (e.g.print myList[2:]will print['c', 'd', 'e']).As a third note, you can even do
print myList[:]where no index is indicated, which will basically return a copy of the entire list (equivalent tomyList[0:len(myList)], returns [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]). This might be useful if you think myList is going to change at some point but you want to keep a copy of it in its current state.If you’re not already doing it I find just messing around in a Python interpreter a whole bunch a big help towards understanding these things. I recommend IPython.