List of Lists in Python

In Python, a list of lists is a nested data structure where each element in the main list is itself another list.

It is useful for representing two-dimensional data structures like matrices, tables, or grids.

Creating a list of lists

You can define a list of lists manually by including lists as elements of a parent list.

For example:

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

For better readability, the above code can also be written on multiple lines as follows:

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

Accessing Elements in a List of Lists

You can access elements in a nested list using the row and column indices.

You can visualize a list of lists like a grid or a table.

      0   1   2  (Column/Inner Index)
    +---+---+---+
  0 | 1 | 2 | 3 |
    +---+---+---+
  1 | 4 | 5 | 6 |
    +---+---+---+
  2 | 7 | 8 | 9 |
    +---+---+---+
(Row/Outer Index)

For example:

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

# Accessing the second row
row2 = matrix[1]
print(row2) # Output: [4, 5, 6]

# Accessing the element '5'
element = matrix[1][1]
print(element) # Output: 5


# Accessing the element '9'
element = matrix[2][2]
print(element) # Output: 9

Indices in Python start at the position 0.

Modifying elements in a list of lists

You can modify the elements in a list of lists using the row and column indices.

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

# Change the element at row 0 and column 2 (value 3) to 99
matrix[0][2] = 99
print(matrix) # Output: [[1, 2, 99], [4, 5, 6], [7, 8, 9]]

# Change the element at row 1 and column 0 (value 4) to 88
matrix[1][0] = 88
print(matrix) # Output: [[1, 2, 99], [88, 5, 6], [7, 8, 9]]

Iterating through a list of lists

You can use a nested for loop to iterate through all the elements of a list of lists.

For example:

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

for row in matrix:
    for element in row:
        print(element, end=" ") # Print each element followed by a space

# Output: 1 2 3 4 5 6 7 8 9