1 / 28
Python Data Structures · Grade 8 · Chapter 5

Lists & Dictionaries

Structuring complex collections, mastering indexing, slicing, key-value mappings, and nested data manipulation.

Real-World Case Study

Managing 100,000 Online Store Products

Imagine an online retailer trying to store catalog items using individual variables: item1_name, item1_price, item2_name... It would be impossible to search or update!

Solution: Lists provide ordered sequences; Dictionaries provide instant labeled lookups.
Lesson Objectives

What We Will Master Today

Prior Knowledge Connection

Single Variables vs. Collections

Single Variables

Holds only one value at a time: score = 95. Requires creating hundreds of variables for datasets.

Collection Data Types

Holds thousands of elements under a single variable name: scores = [95, 88, 72, 100].

Core Concept 1

Python Lists: Ordered & Mutable

Lists are zero-indexed sequences enclosed in square brackets []. Mutability means their elements can be modified after creation.

tools = ["nmap", "wireshark", "metasploit", "burp"] print(tools[0]) # "nmap" (First item) print(tools[-1]) # "burp" (Last item - negative index) tools[1] = "tshark" # Mutates second item
Indexing & Slicing

List Slicing Mechanics: `[start:stop:step]`

Extract sub-lists cleanly using slice notation (note: stop index is exclusive!):

nums = [10, 20, 30, 40, 50, 60] print(nums[1:4]) # [20, 30, 40] (indices 1, 2, 3) print(nums[:3]) # [10, 20, 30] (first 3 items) print(nums[::2]) # [10, 30, 50] (every 2nd item) print(nums[::-1]) # Reverses list!
Essential List Methods

Modifying Lists Dynamically

Adding Items

.append(item) adds to end.
.insert(index, item) inserts at position.

Removing Items

.pop() removes & returns last item.
.remove(val) deletes first matching value.

Core Concept 2

Iterating Lists with `for` Loops

Loop through items directly or track index positions using enumerate().

users = ["Alice", "Bob", "Charlie"] # Direct iteration for user in users: print(f"User: {user}") # Enumerated iteration with index for idx, user in enumerate(users, start=1): print(f"#{idx}: {user}")
Advanced Python Pattern

List Comprehensions Basics

Create transformed lists in a single, readable line of code.

Traditional `for` Loop

squares = [] for x in range(5): squares.append(x**2)

List Comprehension

squares = [x**2 for x in range(5)] # Output: [0, 1, 4, 9, 16]
Core Concept 3

Python Dictionaries: Key-Value Mappings

Dictionaries store pairs enclosed in curly braces {}. Keys act like unique labels for values.

student = { "name": "Zaid", "grade": 8, "gpa": 3.85, "courses": ["CS", "Math", "Physics"] } print(student["name"]) # "Zaid"
Performance Comparison

List Search vs. Dictionary Lookup

List Search: O(N)

To find a user, Python checks item by item from index 0 to N. Takes long on big datasets!

Dict Hash Lookup: O(1)

Key is instantly converted to memory address via hashing algorithm. Instant lookup!

Safe Access

The `.get()` Method — Preventing KeyErrors

Accessing a non-existent key with dict[key] causes a crash. Using .get() provides a safe fallback default value.

user_data = {"username": "cyber_knight"} # Safe lookup with fallback email = user_data.get("email", "Not Provided") print(email) # Prints "Not Provided" instead of crashing!
Dictionary Iteration

Iterating Keys, Values & Items

scores = {"Alice": 95, "Bob": 88, "Charlie": 92} # Iterate Key-Value pairs with .items() for name, score in scores.items(): print(f"{name} scored {score}") # Keys and Values methods all_names = list(scores.keys()) all_scores = list(scores.values())
Complex Data Modeling

Nested Data: List of Dictionaries

Represent real-world databases and JSON API payloads using lists containing dictionaries.

database = [ {"id": 101, "name": "Laptop", "price": 850.0}, {"id": 102, "name": "Mouse", "price": 25.0} ] # Accessing nested item print(database[0]["name"]) # "Laptop"
Data Traversal

Traversing Nested Data Structures

STEP 1
database
Target outer List container.
STEP 2
[0]
Select first dictionary record at index 0.
STEP 3
["price"]
Extract value matching key "price".
Scenario Analysis

Designing a Student Grade System

DATA MODELING

You need to store names, IDs, attendance records, and exam scores for 30 students. How would you structure this in Python using nested lists and dictionaries?

Discussion: Sketch the dictionary keys needed for each student record.
Spot the Mistake

Common Collection Traps

# Trap 1: IndexError items = ["A", "B"] print(items[2]) # Crashes! Index is 0 or 1. # Trap 2: KeyError profile = {"user": "admin"} print(profile["role"]) # Crashes! Use profile.get("role") # Trap 3: Modifying list during iteration
Guided Practice

Contact Book Application Logic

contacts = {} def add_contact(name, phone): contacts[name] = phone def search_contact(name): return contacts.get(name, "Contact not found") add_contact("Laila", "+966500000000") print(search_contact("Laila"))
Hands-on Challenge

Shopping Cart Price Calculator

Given the following list of cart items, calculate total cost and identify the most expensive item:

cart = [ {"item": "Keyboard", "price": 45.0}, {"item": "Monitor", "price": 220.0}, {"item": "Cable", "price": 12.5} ]
Check Your Understanding

What does `[10, 20, 30, 40][-2]` evaluate to?

A10
B20
C30
D40
Click to reveal answer
Check Your Understanding

Which dictionary method returns key-value tuples for iteration?

A.keys()
B.values()
C.items()
D.pairs()
Click to reveal answer
Check Your Understanding

What happens when using `dict.get("missing_key", 0)`?

APython raises a KeyError exception
BIt returns 0 safely without crashing
CIt creates a new key in the dictionary with value 0
DIt deletes the dictionary object
Click to reveal answer
Check Your Understanding

How do you add an element to the end of a list?

Alist.add(item)
Blist.append(item)
Clist.push(item)
Dlist.insert_end(item)
Click to reveal answer
Choosing Data Structures

List vs. Dictionary vs. Set

Use a List When...

Order matters and items may repeat (e.g., historical audit logs).

Use a Dict When...

You need fast lookup by labeled keys (e.g., user profiles).

Use a Set When...

You need unique items only with no duplicates (e.g., unique IP addresses).

Inventory Manager Mini-Project

Building an Inventory Tracker Shell

Write a function update_stock(inventory, item_name, qty_change) that updates quantity or adds new items to an inventory dictionary.

Chapter Summary

Data Structures Master Reference

Exit Ticket

Quick Data Parsing Challenge

data = {"scores": [85, 90, 95]}
Question: Write the exact line of Python code to print the number 90 from `data`.
Looking Ahead

Next Chapter: Prompt Engineering

Now that we understand how data is structured in memory, we will explore how Large Language Models structure prompts to generate precise responses!