Lesson 5 of 40
Foundations
Beginner
โฑ 30 min
Lists, Tuples, Sets & Dicts
Master Python's core data structures โ lists, tuples, sets, and dictionaries โ with slicing, comprehensions, and practical patterns.
Part 1: Lists โ Mutable Sequences
fruits = ["apple","banana","cherry"]
fruits.append("date")
fruits.insert(0, "avocado")
fruits.remove("banana")
last = fruits.pop() # removes & returns last
# Slicing
nums = [0,1,2,3,4,5]
nums[1:4] # [1, 2, 3]
nums[::-1] # [5, 4, 3, 2, 1, 0] (reverse)
nums[-3:] # [3, 4, 5]
fruits.append("date")
fruits.insert(0, "avocado")
fruits.remove("banana")
last = fruits.pop() # removes & returns last
# Slicing
nums = [0,1,2,3,4,5]
nums[1:4] # [1, 2, 3]
nums[::-1] # [5, 4, 3, 2, 1, 0] (reverse)
nums[-3:] # [3, 4, 5]
Part 2: Dictionaries โ Key-Value Mapping
user = {"name":"Alice", "age":30, "active":True}
# Safe get with default
role = user.get("role", "user") # "user"
# Merge dicts (Python 3.9+)
defaults = {"theme":"dark","lang":"en"}
settings = defaults | user # merge
# setdefault
user.setdefault("role", "viewer") # only sets if missing
# Iteration
for key, val in user.items():
print(f"{key}: {val}")
# Safe get with default
role = user.get("role", "user") # "user"
# Merge dicts (Python 3.9+)
defaults = {"theme":"dark","lang":"en"}
settings = defaults | user # merge
# setdefault
user.setdefault("role", "viewer") # only sets if missing
# Iteration
for key, val in user.items():
print(f"{key}: {val}")
Part 3: Sets & Frozensets
tags = {"python","web","api"}
tags.add("fastapi")
tags.discard("web") # safe remove (no error if missing)
# Set operations
a = {1,2,3}; b = {2,3,4}
a | b # union {1,2,3,4}
a & b # intersection {2,3}
a - b # difference {1}
a ^ b # symmetric difference {1,4}
tags.add("fastapi")
tags.discard("web") # safe remove (no error if missing)
# Set operations
a = {1,2,3}; b = {2,3,4}
a | b # union {1,2,3,4}
a & b # intersection {2,3}
a - b # difference {1}
a ^ b # symmetric difference {1,4}
Part 4: Tuples & Unpacking
point = (3.5, 7.2) # immutable
x, y = point # unpacking
# Extended unpacking
first, *rest = [1,2,3,4,5]
# first=1, rest=[2,3,4,5]
# Swap variables elegantly
a, b = 1, 2
a, b = b, a # a=2, b=1
x, y = point # unpacking
# Extended unpacking
first, *rest = [1,2,3,4,5]
# first=1, rest=[2,3,4,5]
# Swap variables elegantly
a, b = 1, 2
a, b = b, a # a=2, b=1
๐ Want the complete guide with projects?
Get the book โ