Python allows very flexible, practical and usable indexing schemes on sequences. Here we will do some basic experiments with indexing.
Let's create a simple string.
a='ThisIsAwesome'
You can access the i'th element in any sequence as: seq[i]. Indexing starts at 0 in Python.
print a[0]
You can access all elements following and including the i'th element as: seq[i:]
print a[1:]
Note that if the result of any indexing operation on a sequence is more than one element, it is stored in a sequence of the same type.
print type(a[1:])
You can access all elements before the i'th element as: seq[:i]. Note that the i'th element is not included. This can be used to print the first 5 elements of the sequence as follows.
print a[:5]
seq[i:j] will give you the elements starting at i and terminating before j.
print a[1:5]
If you want to skip any number of characters while indexing between two indices i and j, use: seq[i:j:skip]. This will return every skip-1 element between i (included) and j (not included).
print a[1:7:2]
Thus, if skip=1 then no skipping takes place when using seq[i:j:skip]
print a[1:7:1]
If you want to access elements till the end with a skip, simply drop out the second index (j).
print a[1::2]
The same thing works if you do not specify the first index.
print a[::2]
While we are on the subject, if you want to access all, the use:
print a[:]
Python also support negative indexing. Positive indexing begins at the start of the sequence at 0. Negative indexing begins at the end of the sequence with -1. Thus seq[-1] will return the last element of the sequence.
print a[-1]
You can use negative indexing to print out the last five elements int he sequence as follows:
print a[-5:]
You can also combine positive and negatice indexing with skipping and do everything you have done above. Try figuring out what the following line is doing.
print a[-8:10:2]
Now try doing some indexing operations with lists and tuples.