Indexing single elements

To access the individual elements in a list, we use indexing. The index of the required element is passed within the square brackets that follow the list name.


my_list = [num for num in range (1,6)]
element = my_list[2]

Remember that in a list, the index of the first element starts from 0, and we add 1 for each subsequent element.

Indexing portions of the list

List slicing is a quick way to access a portion of a list by specifying the start and end indices.

my_list = [num for num in range (1,6)]
my_list = [1, 5, 10, 15, 20, 25, 30, 35, 40]
my_new_list = [2:5]

The list slicing section covers the syntax of this technique in detail.

Negative indexing

In addition to positive indexing, Python also supports negative indexing, which makes lists even more interesting! We use -1 to refer to the last element, -2 to the second-to-last element, and so on.

For instance, to access the last element of my_list, we can simply use the code below:

my_list = [num for num in range (1,6)]
last_element = my_list[-1]

Out of range index values

If we try to access an index that is out of range, it will result in an IndexError. To avoid such errors, exception handling can be incorporated in the code.

my_list = [num for num in range (1,6)]
element = my_list[10]
except IndexError:
print("Index is out of range!")