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']
print(arr[0])
>> 'a'
You can access the second element in the list by index 1
, third element by index 2
and so on:
print(arr[1])
>> 'b'
print(arr[2])
>> '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:
print(arr[-1])
>> 'd'
print(arr[-2])
>> '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