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:
- Master List Slicing and Methods.
- Understand why and when to use Tuples.
- Perform efficient data lookups using Dictionaries.
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.
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.
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
- Store contacts where the key is the Name and the value is a List [Phone, Email].
- Allow the user to search for a contact and see their details.
- Add a new contact to the book.
Step-by-Step Process
- Initialize an empty dictionary.
- Use a loop to take inputs from the user.
- Use
if name in contactsto check for existence before searching.
Expected Deliverables
contacts.pysource code.