Python Basics

Course by zooboole,

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

Introduction to Nested Lists

In Python, a nested list is simply a list inside another list. This allows us to organize
data in a structured way, similar to tables or matrices in mathematics.

For example, a regular list:

numbers = [1, 2, 3, 4, 5]
  • A nested list of them would be:
nested_numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Why Use Nested Lists?

Nested lists are useful because they:

  • Allow us to represent tabular data (like spreadsheets and tables).
  • Help store complex hierarchical structures (e.g., a list of student records).
  • Make it easy to group related data in an organized way.

Example: Representing a Table

Imagine we have student grades in different subjects:

grades = [
    ["Alice", 85, 90, 78],
    ["Bob", 88, 76, 95],
    ["Charlie", 92, 89, 85]
]

Each sublist contains:

  • A student’s name.
  • Their grades in different subjects.

In the next lessons, we will explore how to access, modify, and process data inside nested lists. For the meantime, try the following exercise:

Exercise: Try It Yourself!

  1. Create a nested list that represents a shopping list with different categories (e.g., fruits, dairy, snacks).
  2. Print out the entire nested list.
  3. Try accessing a specific item from one of the sublists.

Example structure for your shopping list

shopping_list = [
    ["Fruits", "Apples", "Bananas", "Oranges"],
    ["Dairy", "Milk", "Cheese"],
    ["Snacks", "Chips", "Chocolate"]
]