Python - Lists & Tuples
Overview
Estimated time: 30–40 minutes
Work with lists and tuples: creation, indexing, slicing, methods, and when to choose one over the other.
Learning Objectives
- Create and manipulate lists and tuples safely.
- Use slicing effectively to copy or extract subsequences.
- Decide when immutability (tuples) is beneficial.
Prerequisites
Lists
nums = [10, 20, 30]
nums.append(40)
print(nums[1])
print(nums[:2])
Expected Output:
20\n[10, 20]
Tuples
pt = (3, 4)
print(len(pt))
# pt[0] = 5 # TypeError: immutable
Expected Output: 2
Common Pitfalls
- Confusing shallow copy via slicing vs deep copy for nested lists.
- Trying to modify a tuple (immutable); use a list if mutation is needed.
Checks for Understanding
- How do you copy a list?
- When would you prefer a tuple to a list?
Show answers
new = old[:]
orlist(old)
(shallow copy).- When you want immutability and to signal fixed-size, read-only data.
Exercises
- Slice a list to get the last two elements.
- Unpack a tuple (x, y) and print a formatted string.