Lists, tuples and strings are examples of sequences, but what is so special about sequences? Two of the main features of a sequence is the indexing operation which allows us to fetch a particular item in the sequence and the slicing operation which allows us to retrieve a slice of the sequence i.e. a part of the sequence.
Example 9.5. Using sequences
#!/usr/bin/python # Filename : seq.py shoplist = ['apple', 'mango', 'carrot', 'banana'] # Indexing or 'Subscription' print shoplist[0] print shoplist[1] print shoplist[2] print shoplist[3] print shoplist[-1] print shoplist[-2] # Slicing using a list print shoplist[1:3] print shoplist[2:] print shoplist[1:-1] print shoplist[:] # Slicing using a string name = 'swaroop' print name[1:3] print name[2:] print name[1:-1] print name[:]
apple mango carrot banana banana carrot ['mango', 'carrot'] ['carrot', 'banana'] ['mango', 'carrot'] ['apple', 'mango', 'carrot', 'banana'] wa aroop waroo swaroop
First, we see how to use indexes to get individual items of a sequence. This is also referred to as subscription. Whenever you specify a number to a sequence within square brackets as shown above, Python will fetch you the item corresponding to that position in the sequence. Remember that Python starts counting numbers from 0. Hence, shoplist[0] fetches the first item and shoplist[3] fetches the fourth item in the shoplist sequence. The index can also be a negative number, in which case, the position is calculated from the end of the sequence. Therefore, shoplist[-1] fetches the last item and shoplist[-2] fetches the second last item in the shoplist sequence.
The slicing operation is used by specifying the name of the sequence followed by an optional pair of numbers separated by a colon, within square brackets. Note that this is very similar to the indexing operation you have been using till now. Remember the numbers are optional when using slices but the colon isn't.
The first number is the position from where the slice starts and the second number is where the slice will stop at. If the first number is left out, Python defaults to the beginning of the sequence. If the second number is left out, Python defaults to the end of the sequence.
Thus, shoplist[1:3] returns a slice of the sequence starting at position 1, includes position 2 but stops at position 3 i.e. it does not include position 3. Therefore a slice of 2 items is returned. Also, shoplist[:] returns a copy of the whole sequence.
You can also try out slicing with negative numbers. Negative numbers are used for positions from the end of the sequence. For example, shoplist[:-1] will return a slice of the sequence which excludes the last item of the sequence.
Try various combinations of such slice specifications using the Python interpreter interactively i.e. the prompt so that you can see the results quickly. The great thing about sequences is that you can access tuples, lists and strings all in the same way.