0
0
Pythonprogramming~5 mins

Nested lists in Python

Choose your learning style9 modes available
Introduction

Nested lists let you store lists inside another list. This helps organize data in groups, like a list of lists.

When you want to store a grid or table of values, like rows and columns.
When you need to group related items together inside a bigger list.
When you want to represent complex data like a list of students, where each student has a list of grades.
When you want to loop through multiple levels of data, like a list of shopping lists.
When you want to build structures like matrices or adjacency lists for graphs.
Syntax
Python
nested_list = [
    ['item1', 'item2', 'item3'],
    ['item4', 'item5', 'item6'],
    ['item7', 'item8', 'item9']
]

Each item inside the main list can itself be a list.

You can access elements using two sets of square brackets: nested_list[row][column]

Examples
This shows an empty nested list with no inner lists.
Python
empty_nested_list = []
print(empty_nested_list)
A nested list with one inner list and one element. Accessing that element prints 42.
Python
single_element_nested_list = [[42]]
print(single_element_nested_list[0][0])
Inner lists can have different lengths. This prints 5 from the second inner list.
Python
mixed_nested_list = [[1, 2], [3, 4, 5], []]
print(mixed_nested_list[1][2])
Accessing the last element (60) in the last inner list.
Python
access_last_element = nested_list = [[10, 20], [30, 40], [50, 60]]
print(nested_list[2][1])
Sample Program

This program creates a nested list like a 3x3 grid, prints it, changes the middle value, and prints it again.

Python
def print_nested_list(nested_list):
    for row_index, inner_list in enumerate(nested_list):
        print(f"Row {row_index}: {inner_list}")

# Create a nested list representing a 3x3 grid
grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print("Original nested list:")
print_nested_list(grid)

# Change the middle element
grid[1][1] = 55

print("\nNested list after changing the middle element:")
print_nested_list(grid)
OutputSuccess
Important Notes

Accessing elements in nested lists takes two steps: first the outer list, then the inner list.

Time complexity to access an element is O(1) because lists allow direct access by index.

Be careful with empty inner lists; trying to access elements inside them causes errors.

Use nested lists when you need simple multi-level grouping. For more complex data, consider other structures like dictionaries.

Summary

Nested lists store lists inside lists to organize data in multiple levels.

You access elements with two sets of brackets: outer and inner indexes.

They are useful for grids, tables, and grouped data.