Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Lists of Lists

A list of lists is a special type of nested list where each element of the main list is itself a list.
This structure is commonly used to represent tabular data, matrices, or hierarchical structures.

Creating a List of Lists

A basic example of a list of lists:

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

Output

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  • Each sublist represents a row in the table

Accessing Elements in a List of Lists

To access elements, use double indexing:

print(matrix[0])     # Output: [1, 2, 3]  (First row)
print(matrix[1][2])  # Output: 6  (Second row, third column)

Modifying Elements in a List of Lists

You can update values using their index:

matrix[2][1] = 99   # Change 8 to 99
print(matrix)

New output:

[[1, 2, 3], [4, 5, 6], [7, 99, 9]]

Exercise: Try It Yourself!

  1. Create a list of lists representing a classroom of students, where each student has:
    • A name
    • Their age
    • Their test scores (list of numbers)
  2. Print the full list.
  3. Access the second student's name.
  4. Update the third student's test score.