Free preview

100 lessons

Python Done Right

Free preview

Python Done Right · 100 lessons

Learn Python from scratch - syntax through to OOP

No surprise gaps

Actually remember it

Skip what you know

One subscription. All learning paths included.

Our content is best on a larger screen

List indexing

List indexing

Explanation

We access list elements using square brackets [] with an index. Python uses zero-based indexing, so the first element is at index 0:

elements = ['hydrogen', 'helium', 'lithium', 'beryllium']
print(elements[0])  # Output: hydrogen
print(elements[2])  # Output: lithium

Negative indexing counts from the end of the list:

print(elements[-1])  # Output: beryllium (last)
print(elements[-2])  # Output: lithium (second-to-last)

Practice questions

4 questions

In the Python Console, there is a variable called my_list defined which is a list of integers. Find the value of the 45th element.

Once you've determined the value, assign it to a variable called answer and submit.

+ 3 more questions

Indexing nested lists

Explanation

Lists can contain other lists, creating nested structures. A list of lists is often called a matrix (2D), and a list of lists of lists is called a cube (3D).

Matrices (2D)

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

To access an element, use two indices: matrix[row][column].

print(matrix[0][0])  # Output: 1 (first row, first column)
print(matrix[1][2])  # Output: 6 (second row, third column)
print(matrix[2][0])  # Output: 7 (third row, first column)

Cubes (3D)

A cube is a sequence of matrices, one behind the other:

cube = [
    [[1, 2], [3, 4]],   # matrix 0
    [[5, 6], [7, 8]]    # matrix 1
]

To access an element, use three indices: cube[matrix][row][column].

  • First index: which matrix in the stack
  • Second index: which row in that matrix
  • Third index: which column in that row
print(cube[1][1][0])  # Output: 7
Step-by-step breakdown

Details

Practice questions

4 questions

In the Python Console, a variable matrix contains a 2D list. Write an expression that accesses the element in the 2nd row and 3rd column, and assign it to a variable named answer.

+ 3 more questions

IndexError

Explanation

Accessing an index that doesn't exist raises an IndexError:

my_list = [10, 20, 30]
print(my_list[3])  # IndexError: list index out of range

A list with n elements has valid indices from 0 to n-1. Here, my_list has 3 elements (indices 0, 1, 2), so index 3 is out of range.

Practice questions

4 questions

When Python encounters an error because the code violates its rules, the resulting message can be difficult to read, especially as a beginner. However, it's useful to try to extract as much information from it as possible.

In the Python Editor or Console, create a list with a few elements then try to access an element at an index that doesn't exist. What message is displayed after the text IndexError?

Select the correct answer:

+ 3 more questions