Nested lists let you store lists inside another list. This helps organize data in groups, like a list of lists.
Nested lists in 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]
empty_nested_list = []
print(empty_nested_list)single_element_nested_list = [[42]] print(single_element_nested_list[0][0])
mixed_nested_list = [[1, 2], [3, 4, 5], []] print(mixed_nested_list[1][2])
access_last_element = nested_list = [[10, 20], [30, 40], [50, 60]] print(nested_list[2][1])
This program creates a nested list like a 3x3 grid, prints it, changes the middle value, and prints it again.
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)
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.
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.