Python Language Indexing and Slicing Basic Indexing

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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

Got any Python Language Question?