We are thrilled to inform you that Lancecourse is becoming INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

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.