Chapter 4 — Python Data Structures

📚 Chapter Overview

Real-world data is complex. In this chapter, you will master Python's powerful built-in collections: Lists (mutable sequences), Tuples (immutable sequences), and Dictionaries (key-value pairs).

Learning Objectives:

4.1 Lists and Slicing

Part 1 — Definition

A List is an ordered collection of items which is changeable (mutable). Lists allow duplicate members and can hold different data types. Slicing is a powerful way to extract a sub-portion of a list using [start:stop:step].

Part 2 — Syntax

my_list = [10, 20, 30, 40]
print(my_list[1:3]) # Output: [20, 30]
my_list.append(50)

Part 3 — Example

Problem: Manage a "To-Do" list and remove the completed task.

script.py
tasks = ["Code", "Eat", "Sleep"]
tasks.append("Repeat")
tasks.pop(1) # Removes "Eat"
print(tasks)

Part 4 — Video

Video: Coming Soon


4.2 Dictionaries (Key-Value Pairs)

Part 1 — Definition

A Dictionary is an unordered, changeable, and indexed collection. They are written with curly brackets and have Keys and Values. Dictionaries are extremely fast for looking up information if you know the key.

Part 2 — Syntax

user = {"name": "Ali", "age": 25}
print(user["name"])

Part 3 — Example

Problem: Store student grades and update one.

script.py
grades = {"Math": 90, "Science": 85}
grades["Math"] = 95 # Update
grades["History"] = 80 # Add new
print(grades)

Observation: Dictionary keys must be unique; if you use the same key again, the value will be overwritten.

Part 4 — Video

Video: Coming Soon


🏆 Chapter Challenge

Challenge Objective

Build a "Contact Book Application" using a dictionary of lists.

Requirements

Step-by-Step Process

  1. Initialize an empty dictionary.
  2. Use a loop to take inputs from the user.
  3. Use if name in contacts to check for existence before searching.

Expected Deliverables

Solve in Compiler