Python Data Structures

Python has four built-in data structures that you'll use every day: lists, dictionaries, tuples, and sets. Mastering them is key to writing Pythonic code.

Lists — Ordered, Mutable Collections

Python
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, None]  # Any types
nested = [[1, 2], [3, 4], [5, 6]]       # 2D list

# Accessing elements
print(fruits[0])      # "apple" (first element)
print(fruits[-1])     # "cherry" (last element)
print(fruits[1:3])    # ["banana", "cherry"] (slice)

# Modifying lists
fruits.append("date")         # Add to end
fruits.insert(1, "avocado")   # Insert at index 1
fruits.extend(["elderberry", "fig"])  # Add multiple
fruits.remove("banana")       # Remove by value
fruits.pop()                  # Remove and return last
fruits.pop(0)                 # Remove and return first
del fruits[0]                 # Remove by index

# Useful methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()                # Sort in place: [1, 1, 2, 3, 4, 5, 6, 9]
numbers.reverse()             # Reverse in place
print(len(numbers))           # 8 (length)
print(numbers.count(1))       # 2 (occurrences of 1)
print(numbers.index(4))       # 4 (index of first 4)

List Comprehensions — Python's Superpower

Python
# Basic syntax: [expression for item in iterable if condition]

# Square numbers
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Filter even numbers
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Transform strings
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
# ["ALICE", "BOB", "CHARLIE"]

# Flatten nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

# With condition and expression
scores = [85, 92, 78, 95, 88]
results = [f"{'PASS' if s >= 80 else 'FAIL'}: {s}" for s in scores]
# ['PASS: 85', 'PASS: 92', 'FAIL: 78', 'PASS: 95', 'PASS: 88']

Dictionaries — Key-Value Pairs

Python
# Creating dictionaries
person = {
    "name": "Alice",
    "age": 28,
    "email": "alice@example.com"
}

# Accessing values
print(person["name"])             # "Alice"
print(person.get("phone", "N/A")) # "N/A" (default if key missing)

# Modifying dictionaries
person["age"] = 29               # Update
person["phone"] = "555-1234"     # Add new key
del person["email"]              # Remove key
person.update({"city": "NYC", "age": 30})  # Update multiple

# Dictionary methods
print(person.keys())             # dict_keys(['name', 'age', ...])
print(person.values())           # dict_values(['Alice', 29, ...])
print(person.items())            # dict_items([('name', 'Alice'), ...])
print("name" in person)          # True (check if key exists)

# Dictionary comprehension
word_lengths = {word: len(word) for word in ["hello", "world", "python"]}
# {'hello': 5, 'world': 5, 'python': 6}

# Nested dictionaries
students = {
    "alice": {"math": 95, "science": 88},
    "bob": {"math": 78, "science": 92},
}
print(students["alice"]["math"])  # 95

Tuples — Immutable Sequences

Python
# Tuples are like lists but can't be modified
coordinates = (10, 20)
rgb_color = (255, 128, 0)
single = (42,)  # Note the comma for single-element tuple!

# Access (same as lists)
print(coordinates[0])  # 10
print(coordinates[-1])  # 20

# Unpacking (powerful!)
x, y = coordinates
print(x, y)  # 10 20

# Swap variables (Pythonic!)
a, b = 1, 2
a, b = b, a  # Now a=2, b=1

# Named tuples (readable tuples)
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y)  # 3 4

# Tuples as dict keys (lists can't be!)
locations = {(40.7, -74.0): "New York", (51.5, -0.1): "London"}

Sets — Unique, Unordered Collections

Python
# Creating sets
colors = {"red", "green", "blue"}
numbers = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3} — duplicates removed!

# Set operations
colors.add("yellow")         # Add element
colors.discard("red")        # Remove (no error if missing)
colors.remove("green")       # Remove (KeyError if missing)

# Set math
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}

print(a | b)    # Union: {1, 2, 3, 4, 5, 6, 7, 8}
print(a & b)    # Intersection: {4, 5}
print(a - b)    # Difference: {1, 2, 3}
print(a ^ b)    # Symmetric difference: {1, 2, 3, 6, 7, 8}

# Practical: remove duplicates from a list
items = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = list(set(items))  # [1, 2, 3, 4]

Knowledge Check

4 questions — test your understanding

1

What is the output of: [x**2 for x in range(5)]?

2

Which data structure is IMMUTABLE?

3

What does {'a': 1, 'b': 2}.get('c', 0) return?

4

How do you create an empty set in Python?