As I mentioned here: A sequence is a special data structure in Python where data elements can be referenced thru numbers, an index so to speak.
This hasnt been the entire truth. Actually data elements in a sequence can be also referenced thru ranges, a pair of start and end index so to speak, separated by a colon. This would return another string when used on a string or another list when used on lists. Neither the start nor the end index has to be specified: 0 would be the default for the start index, and when no ending index is specified then the sequence will be returned up to the very end.
Negative indexing can be used to index a sequence from the right ( or from the end ). Thus 1 addresses the last element in a sequence.
Those ranges always specify the first element to retrieve and the last element not to retrieve, thus [0:2] would tell Python to get the first and second element of the sequence and stop at the third element ( the one with index 2; remember: indexing starts with 0 ). [0:-1] would tell Python to get all the elements from a sequence except the last one.
Here are a few examples done with a string:
>>> str = "We will we will rock you !"
'will we will rock '
'We will we will rock you'
'We will we will rock you !'
0 blog comments below