Python Language Indexing and Slicing Basic Indexing


Python lists are 0-based i.e. the first element in the list can be accessed by the index 0

arr = ['a', 'b', 'c', 'd']
>> 'a'

You can access the second element in the list by index 1, third element by index 2 and so on:

>> 'b'
>> 'c'

You can also use negative indices to access elements from the end of the list. eg. index -1 will give you the last element of the list and index -2 will give you the second-to-last element of the list:

>> 'd'
>> 'c'

If you try to access an index which is not present in the list, an IndexError will be raised:

print arr[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range