← Back to Python series
🌱
Basic
Indexing · Slicing · Methods · Unpacking

Week 6 — Lists & Tuples

Work with Python's most-used sequence types. Master list CRUD operations, slicing syntax, common list methods, and tuple unpacking.

listtupleslicingmethodsunpacking
Duration
2.5 hours
Level
📊 Beginner
Prerequisite
🎯 Week 5
OUTCOME
Build a contacts list that supports add, remove, search, and sort

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.

python
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))  # 4

2. Slicing

python
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]  reversed

3. Common List Methods

MethodDescriptionExample
append(x)Add to endlst.append(5)
insert(i, x)Insert at indexlst.insert(0, 'a')
remove(x)Remove first matchlst.remove('a')
pop(i)Remove & return at ilst.pop()
sort()Sort in-placelst.sort()
reverse()Reverse in-placelst.reverse()
index(x)Find first indexlst.index(3)
count(x)Count occurrenceslst.count(2)

4. Tuples

Tuples are like lists but immutable (cannot be changed after creation). Use them for fixed data.

python
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 10

5. 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.

QuestionListTuple
Mutable?Yes — add / remove / reassignNo — fixed after creation
Use it forA growing collection of similar itemsA 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.

python
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)         # unchanged
⚠️

A 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.

01_list_basics.pyCRUD operations on a list
CODE
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}")
▶ Output
1. Alice
2. Charlie
3. Diana
4. Eve
02_slicing.pySlice operations
CODE
data = 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])
▶ Output
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]
03_tuple_unpack.pyTuple creation and unpacking
CODE
# 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}")
▶ Output
Point: (10, 20)
a=200, b=100
min=1, max=9

📝 Exercises

Try them yourself first, then open the solution to compare.

Exercise 1

Grade Statistics

Goal: Read 5 scores, then print the sum, average, max, and min.

Requirements
  • Read 5 integers into a list
  • Use sum(), max(), min(), len()
  • Print all four statistics
Sample I/O
Enter 5 scores:
85 90 78 92 88
Sum: 433  Avg: 86.6  Max: 92  Min: 78
Toggle solution
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)}')
Exercise 2

List Rotation

Goal: Rotate a list k positions to the right without using deque.

Requirements
  • Read a list and k from input
  • Implement rotation using slicing
  • Print the rotated list
Sample I/O
List: 1 2 3 4 5
k: 2
[4, 5, 1, 2, 3]
Toggle solution
SOLUTION
lst = list(map(int, input('List: ').split()))
k = int(input('k: ')) % len(lst)
print(lst[-k:] + lst[:-k])
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗