Lists

Accessing Lists

Explore how to access individual elements and portions of Python lists using indexing and slicing techniques. Learn about positive and negative indexing and how to manage errors when accessing invalid indices.

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.

Syntax

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

Indexing single elements in Python

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[start:end] my_list = [1, 5, 10, 15, 20, 25, 30, 35, 40] my_new_list = [2:5] print(my_new_list)

Indexing portions of a list in Python

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] print(last_element)

Negative indexing in Python

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)] try: element = my_list[10] except IndexError: print("Index is out of range!")

Out of range index values

On this page

    In This Module