Skip to content

Chapter 5: Data Structures

List — The Universal Storage Box 📦

A list is like a numbered storage box — items can be put in, taken out, or rearranged at any time. It's the most commonly used data structure in Python.

bash
# Create lists
fruits = ["Apple", "Banana", "Orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14, None]  # Can mix types

# Access elements (indexing starts at 0!)
print(fruits[0])      # First element
print(fruits[-1])     # Last element
print(fruits[1:3])    # Slice: 2nd to 3rd

# Common operations
fruits.append("Mango")         # Add to end
fruits.insert(0, "Strawberry") # Insert at position
fruits.remove("Banana")        # Remove specific element
popped = fruits.pop()          # Remove and return last element
fruits.sort()                  # Sort

print(f"Final list: {fruits}")
print(f"List length: {len(fruits)}")
bash
Apple
Orange
['Banana', 'Orange']
Final list: ['Strawberry', 'Orange', 'Mango', 'Apple']
List length: 4
bash
# List comprehension (Python's "syntactic sugar")
squares = [x ** 2 for x in range(1, 6)]
print(f"Squares: {squares}")

evens = [x for x in range(20) if x % 2 == 0]
print(f"Even numbers: {evens}")

# Nested lists (2D list)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(f"Matrix row 2, col 3: {matrix[1][2]}")
bash
Squares: [1, 4, 9, 16, 25]
Even numbers: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Matrix row 2, col 3: 6

Tuple — The Unchangeable List 📜

If a list is a storage box, then a tuple is a "wax-sealed envelope" — once sealed, it cannot be modified. Suitable for storing data that should never change.

bash
# Create tuples
point = (3, 4)
rgb_color = (255, 128, 0)
single = (42,)  # Note: single-element tuples must have a trailing comma!

# Access elements
print(f"Coordinates x={point[0]}, y={point[1]}")

# Tuple unpacking
x, y = point
print(f"After unpacking: x={x}, y={y}")

# Trying to modify a tuple raises an error
try:
    point[0] = 10
except TypeError as e:
    print(f"Error: {e}")

# Tuple trick: returning multiple values from a function
def get_min_max(data):
    return min(data), max(data)

lo, hi = get_min_max([3, 1, 4, 1, 5, 9])
print(f"Min={lo}, Max={hi}")
bash
Coordinates x=3, y=4
After unpacking: x=3, y=4
Error: 'tuple' object does not support item assignment
Min=1, Max=9

Dictionary — The Phone Book 📒

A dictionary is like a phone book: you quickly find a phone number (value) by name (key). Each key is unique, and lookup speed is extremely fast.

bash
# Create dictionary
student = {
    "name": "Alice",
    "age": 18,
    "grades": [85, 92, 78],
    "is_active": True
}

# Access values
print(f"Name: {student['name']}")
print(f"Gender: {student.get('gender', 'Unknown')}")  # Use get to avoid KeyError

# Add, modify, delete
student["email"] = "xiaoming@example.com"  # Add
student["age"] = 19                         # Modify
del student["is_active"]                    # Delete

# Iterate dictionary
print("\nStudent info:")
for key, value in student.items():
    print(f"  {key}: {value}")

# Dictionary comprehension
square_map = {x: x**2 for x in range(1, 6)}
print(f"\nSquare mapping: {square_map}")
bash
Name: Alice
Gender: Unknown

Student info:
  name: Alice
  age: 19
  grades: [85, 92, 78]
  email: xiaoming@example.com

Square mapping: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Set — The Non-Duplicate Lottery Box 🎰

A set is like a lottery box: each number can only appear once, and there's no order. It excels at "deduplication" and "set operations."

bash
# Create sets
colors_a = {"Red", "Blue", "Green", "Yellow"}
colors_b = {"Blue", "Yellow", "Purple", "White"}

# Automatic deduplication
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = set(numbers)
print(f"Deduplicated: {unique}")

# Set operations
print(f"Intersection (in both): {colors_a & colors_b}")
print(f"Union (all): {colors_a | colors_b}")
print(f"Difference (A only): {colors_a - colors_b}")
print(f"Symmetric difference (unique to each): {colors_a ^ colors_b}")
bash
Deduplicated: {1, 2, 3, 4}
Intersection (in both): {'Blue', 'Yellow'}
Union (all): {'Red', 'Blue', 'Green', 'Yellow', 'Purple', 'White'}
Difference (A only): {'Red', 'Green'}
Symmetric difference (unique to each): {'Red', 'Green', 'Purple', 'White'}
Featurelisttupledictset
Syntax[ ]( )
Ordered✅ Yes✅ Yes✅ Yes (3.7+)❌ No
Mutable✅ Yes❌ No✅ Yes✅ Yes
Duplicates✅ Yes✅ YesKeys unique❌ No
Use caseOrdered collectionFixed dataKey-value mappingDedup, set operations