Week 6 — Lists & Tuples
Work with Python's most-used sequence types. Master list CRUD operations, slicing syntax, common list methods, and tuple unpacking.
What you'll learn
- 1Create and modify lists
- 2Access elements by index and slice
- 3Use append, insert, remove, pop, sort, reverse
- 4Understand the difference between list and tuple
- 5Unpack sequences into variables
1. Lists
Lists are ordered, mutable sequences. They can hold values of any type.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
fruits.append("date")
fruits.insert(1, "blueberry")
fruits.remove("banana")
print(len(fruits)) # 42. Slicing
nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4]) # [1, 2, 3]
print(nums[:3]) # [0, 1, 2]
print(nums[3:]) # [3, 4, 5]
print(nums[::2]) # [0, 2, 4] every other
print(nums[::-1]) # [5, 4, 3, 2, 1, 0] reversed3. Common List Methods
| Method | Description | Example |
|---|---|---|
| append(x) | Add to end | lst.append(5) |
| insert(i, x) | Insert at index | lst.insert(0, 'a') |
| remove(x) | Remove first match | lst.remove('a') |
| pop(i) | Remove & return at i | lst.pop() |
| sort() | Sort in-place | lst.sort() |
| reverse() | Reverse in-place | lst.reverse() |
| index(x) | Find first index | lst.index(3) |
| count(x) | Count occurrences | lst.count(2) |
4. Tuples
Tuples are like lists but immutable (cannot be changed after creation). Use them for fixed data.
point = (3, 4)
x, y = point # unpacking
print(f"x={x}, y={y}")
rgb = (255, 128, 0)
r, g, b = rgb
# swap without temp variable
a, b = 10, 20
a, b = b, a
print(a, b) # 20 105. List vs Tuple — and the copy trap
Lists and tuples look similar, but picking the right one prevents whole classes of bugs — and understanding how Python copies them prevents the rest.
| Question | List | Tuple |
|---|---|---|
| Mutable? | Yes — add / remove / reassign | No — fixed after creation |
| Use it for | A growing collection of similar items | A fixed record (x, y) or multiple return values |
| Works as a dict key? | No (unhashable) | Yes (hashable) |
| Syntax | [1, 2, 3] | (1, 2, 3) — the comma is what counts |
The copy trap (aliasing)
Assignment never copies a list — it just makes a second name for the SAME list. Mutating through one name shows up in the other. Copy explicitly when you need independence.
a = [1, 2, 3]
b = a # NOT a copy — same list object
b.append(4)
print(a) # [1, 2, 3, 4] <- surprised?
c = a[:] # shallow copy (also list(a) or a.copy())
c.append(5)
print(a) # unchangedA one-element tuple needs the comma: (5,) is a tuple, but (5) is just the integer 5. This bites everyone exactly once.
Common Mistakes (FAQ)
Q. Why does sorted_lst = lst.sort() give me None?
list.sort() sorts in place and returns None. Call it for the side effect (lst.sort()), or use sorted(lst) when you want a brand-new sorted list back.
Q. list[10] on a 5-item list crashes — how do I guard it?
That's an IndexError. Check len(lst) first, use a slice (lst[10:11] returns [] safely), or wrap the access in try/except IndexError.
Q. I did new = old, but editing new changed old too.
new = old doesn't copy — both names point to the same list. Use new = old[:], list(old), or old.copy() for a shallow copy (and copy.deepcopy for nested lists).
Q. Why isn't (5) a tuple?
Parentheses alone don't make a tuple — the comma does. Write (5,) for a one-element tuple; for multiple items like (1, 2) the comma is already there.
Q. When should I pick a tuple over a list?
Use a tuple for a fixed, heterogeneous record (a coordinate, an RGB color, multiple return values) or when you need a hashable dict key. Use a list when the collection grows, shrinks, or gets reordered.
💻 Examples
Run these examples and check the output yourself.
names = ["Alice", "Bob", "Charlie"]
names.append("Diana")
names.insert(1, "Eve")
names.remove("Bob")
names.sort()
for i, name in enumerate(names, 1):
print(f"{i}. {name}")
1. Alice
2. Charlie
3. Diana
4. Evedata = list(range(10)) # [0..9]
print("First 5: ", data[:5])
print("Last 5: ", data[5:])
print("Middle: ", data[3:7])
print("Reversed: ", data[::-1])
print("Every 3rd:", data[::3])
First 5: [0, 1, 2, 3, 4]
Last 5: [5, 6, 7, 8, 9]
Middle: [3, 4, 5, 6]
Reversed: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Every 3rd: [0, 3, 6, 9]# Coordinates
point = (10, 20)
x, y = point
print(f"Point: ({x}, {y})")
# Swap two variables
a, b = 100, 200
a, b = b, a
print(f"a={a}, b={b}")
# Return multiple values from function
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(f"min={lo}, max={hi}")
Point: (10, 20)
a=200, b=100
min=1, max=9📝 Exercises
Try them yourself first, then open the solution to compare.
Grade Statistics
Goal: Read 5 scores, then print the sum, average, max, and min.
- Read 5 integers into a list
- Use sum(), max(), min(), len()
- Print all four statistics
Enter 5 scores:
85 90 78 92 88
Sum: 433 Avg: 86.6 Max: 92 Min: 78▶Toggle solution
scores = [int(input(f'Score {i+1}: ')) for i in range(5)]
print(f'Sum: {sum(scores)} Avg: {sum(scores)/len(scores):.1f} Max: {max(scores)} Min: {min(scores)}')
List Rotation
Goal: Rotate a list k positions to the right without using deque.
- Read a list and k from input
- Implement rotation using slicing
- Print the rotated list
List: 1 2 3 4 5
k: 2
[4, 5, 1, 2, 3]▶Toggle solution
lst = list(map(int, input('List: ').split()))
k = int(input('k: ')) % len(lst)
print(lst[-k:] + lst[:-k])
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗