Indexing in sequences

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.

In [2]:
a='ThisIsAwesome'

You can access the i'th element in any sequence as: seq[i]. Indexing starts at 0 in Python.

In [3]:
print a[0]
T

You can access all elements following and including the i'th element as: seq[i:]

In [4]:
print a[1:]
hisIsAwesome

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.

In [5]:
print type(a[1:])
<type 'str'>

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.

In [6]:
print a[:5]
ThisI

seq[i:j] will give you the elements starting at i and terminating before j.

In [7]:
print a[1:5]
hisI

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).

In [8]:
print a[1:7:2]
hss

Thus, if skip=1 then no skipping takes place when using seq[i:j:skip]

In [9]:
print a[1:7:1]
hisIsA

If you want to access elements till the end with a skip, simply drop out the second index (j).

In [10]:
print a[1::2]
hsswsm

The same thing works if you do not specify the first index.

In [11]:
print a[::2]
TiIAeoe

While we are on the subject, if you want to access all, the use:

In [13]:
print a[:]
ThisIsAwesome

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.

In [21]:
print a[-1]
e

You can use negative indexing to print out the last five elements int he sequence as follows:

In [25]:
print a[-5:]
esome

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.

In [29]:
print a[-8:10:2]
sws

Now try doing some indexing operations with lists and tuples.

(c) Dr. Fayyaz ul Amir Afsar Minhas, DCIS, PIEAS, Pakistan.