Crash Courses · Masters
Data Structures: Lists, Dicts, Sets & Tuples
Master Python's four core data structures and know when to reach for each one.
15 min read+175 XP on completionCert: Python Crash Course
Tap any word in the text below to start reading from there.
Data Structures: Lists, Dicts, Sets & Tuples
Lists — Ordered, Mutable Sequences
# Creating and accessing
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple (0-indexed)
print(fruits[-1]) # cherry (negative: from end)
print(fruits[1:3]) # ['banana', 'cherry'] (slicing)
print(fruits[::-1]) # ['cherry', 'banana', 'apple'] (reversed)
# Mutating a list
fruits.append("mango") # add to end
fruits.insert(1, "blueberry") # insert at index
fruits.remove("banana") # remove by value
popped = fruits.pop() # remove and return last item
fruits.pop(0) # remove by index
# Useful list methods
nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.sort() # sort in-place
print(nums) # [1, 1, 2, 3, 4, 5, 6, 9]
sorted_copy = sorted(nums, reverse=True) # new sorted list
print(nums.count(1)) # 2 — count occurrences
print(nums.index(5)) # 4 — find index of value---
List Comprehensions
# Basic: [expression for item in iterable]
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With filter: [expression for item in iterable if condition]
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Transforming strings
names = [" jordan ", " TONY ", " aria "]
clean = [name.strip().title() for name in names]
print(clean) # ['Jordan', 'Tony', 'Aria']
# Nested comprehension (matrix flattening)
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [n for row in matrix for n in row]
print(flat) # [1, 2, 3, 4, 5, 6]---
Tuples — Ordered, Immutable Sequences
# Tuples are immutable — they cannot be changed after creation
point = (10, 25)
x, y = point # tuple unpacking
print(f"x={x}, y={y}") # x=10, y=25
# Tuples as return values (common pattern)
def get_min_max(lst):
return min(lst), max(lst) # returns a tuple
lo, hi = get_min_max([3, 1, 4, 1, 5, 9])
print(f"Range: {lo}–{hi}") # Range: 1–9
# Named tuples — self-documenting tuples
from collections import namedtuple
Color = namedtuple("Color", ["r", "g", "b"])
red = Color(255, 0, 0)
print(red.r, red.g, red.b) # 255 0 0---
Dictionaries — Key-Value Mappings
user = {"name": "Jordan", "age": 28, "role": "admin"}
# Access
print(user["name"]) # Jordan
print(user.get("email", "N/A")) # N/A (safe access, no KeyError)
# Mutate
user["email"] = "jordan@example.com" # add or update
del user["role"] # delete a key
user.update({"age": 29, "city": "Kingston"}) # merge multiple
# Iterate
for key in user:
print(key)
for key, value in user.items():
print(f"{key}: {value}")
for value in user.values():
print(value)
# Dict comprehension
scores = {"alice": 88, "bob": 74, "carol": 95}
passing = {name: score for name, score in scores.items() if score >= 80}
print(passing) # {'alice': 88, 'carol': 95}
# Nested dict
contacts = {
"jordan": {"phone": "876-555-0101", "email": "j@jst.com"},
"tony": {"phone": "876-555-0202", "email": "t@jst.com"},
}
print(contacts["jordan"]["phone"]) # 876-555-0101---
Sets — Unique Values, Fast Membership Tests
# Sets store unique values only
tags = {"python", "web", "api", "python"} # duplicates removed
print(tags) # {'python', 'web', 'api'} (order not guaranteed)
# O(1) membership test — much faster than list for large collections
print("python" in tags) # True
tags.add("async")
tags.discard("web") # remove without error if missing
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # {1,2,3,4,5,6} — union
print(a & b) # {3,4} — intersection
print(a - b) # {1,2} — difference (in a but not b)
print(a ^ b) # {1,2,5,6} — symmetric difference
# Deduplication pattern
duplicates = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(duplicates))
print(sorted(unique)) # [1, 2, 3, 4]---
When to Use Which Structure
| Need | Use |
|---|---|
| Ordered, changeable sequence | **list** |
| Fixed, immutable sequence (coordinates, records) | **tuple** |
| Key → value lookup | **dict** |
| Unique values, fast membership test | **set** |
Reading progress
0% read
In this module
List
Tuple
Dict
Set
0%