Lists & Tuples
So far, every variable has held one value at a time. Real programs rarely work that way — a shopping cart holds many items, a leaderboard holds many scores, a form submission holds many fields. Lists and tuples are how Python holds a whole collection of values under one name, and this chapter is where that skill starts.
How to read this chapter
- Start with the pattern. Each section teaches one small collection idea at a time.
- Read the example first. The code mirrors real situations like shopping carts, orders, and coordinates.
- Try one line at a time. The playgrounds are meant for quick experiments, not long typing.
1. Creating lists & accessing elements
- List = an ordered collection of values in one variable.
- Indexing and slicing work exactly like they did for strings in Chapter 6.
- Unlike strings, a list can be changed in place.
fruits = ["apple", "banana", "cherry"]. A list can hold
any number of items, of any type, and — unlike a string — its
contents can be changed after it's created.
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(fruits)
print(len(fruits)) # 5 — same len() you already know from strings
Getting one item out of a list uses the same square-bracket indexing
you learned for strings — position numbers count from
0, and negative numbers count from the end:
apple banana cherry date elderberry
[0] [1] [2] [3] [4]
[-5] [-4] [-3] [-2] [-1]
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(fruits[0]) # 'apple' — first item
print(fruits[-1]) # 'elderberry' — last item, no matter the length
# Slicing: [start:stop] — stop is EXCLUDED, same rule as strings/range()
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[-2:]) # ['date', 'elderberry'] — last 2 items
print(fruits[::-1]) # the whole list, reversed
Here's the one big difference from strings: a list is mutable, so you can reach into it by index and overwrite one item without rebuilding the whole thing.
s[0] = "X" crashes with a
TypeError. Lists are mutable —
fruits[1] = "blueberry" just works, and it edits the
same list object instead of creating a new one.
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
fruits[1] = "blueberry" # overwrite one item in place
print(fruits) # ['apple', 'blueberry', 'cherry', 'date', 'elderberry']
Go Deeper: a list can mix types, but usually shouldn't
Python doesn't stop you from writing
mixed = ["Alice", 29, True] — a list can hold any mix
of types. In practice, most real lists hold one consistent kind of
thing (all prices, all names, all orders), because that's what
makes looping over them predictable. Save mixing types for cases
where each item genuinely represents a different field, like a
single record — which is exactly what tuples (Section 3) are
usually for.
- A list is written with square brackets:
[item1, item2, ...], andlen()counts its items. - Indexing (
fruits[i]) and slicing (fruits[a:b:step]) work exactly like they did for strings. - Unlike strings, lists are mutable —
fruits[1] = "x"edits the list in place instead of creating a new one.
2. List methods that grow, shrink, and reorder a list
- Grow a list with
.append(),.insert(),.extend(). - Shrink it with
.remove(),.pop(),.clear(). - Reorder it with
.sort(),sorted(),.reverse().
Three methods add new items to a list, each in a slightly different spot:
.append(x)addsxto the very end..insert(i, x)addsxat positioni, shifting everything after it over..extend(other_list)adds every item fromother_listonto the end, one at a time.
cart = ["headphones", "mouse"]
cart.append("keyboard")
print(cart) # ['headphones', 'mouse', 'keyboard']
cart.insert(1, "webcam")
print(cart) # ['headphones', 'webcam', 'mouse', 'keyboard']
cart.extend(["mousepad", "usb-cable"])
print(cart) # ['headphones', 'webcam', 'mouse', 'keyboard', 'mousepad', 'usb-cable']
.append(x) always adds exactly one new item, even if
x is itself a list — cart.append([1, 2])
adds one item that is a list. .extend(x) instead
unpacks x and adds each of its items individually. Reach
for .extend() whenever you're merging in another list's
contents.
Removing items works a similar way — pick the method based on whether you know the value or the position:
.remove(value)deletes the first item that matchesvalue(crashes withValueErrorif it's not there)..pop()removes and returns the last item;.pop(i)removes and returns the item at positioni..clear()empties the whole list.
cart = ["headphones", "webcam", "mouse", "keyboard", "mousepad", "usb-cable"]
cart.remove("mouse")
print(cart) # drops the first "mouse" it finds
last_item = cart.pop()
print(last_item, cart) # 'usb-cable' popped off the end
first_item = cart.pop(0)
print(first_item, cart) # 'headphones' popped off the front
Finally, three methods change a list's order without adding or removing anything:
scores = [88, 72, 95, 60, 81]
scores.sort() # sorts scores IN PLACE, ascending
print(scores) # [60, 72, 81, 88, 95]
scores.sort(reverse=True) # in place, descending
print(scores) # [95, 88, 81, 72, 60]
# sorted() instead returns a NEW sorted list, leaving the original alone
names = ["Zoe", "Amir", "Priya"]
print(sorted(names)) # ['Amir', 'Priya', 'Zoe'] — a new list
print(names) # ['Zoe', 'Amir', 'Priya'] — unchanged
letters = ["b", "a", "d", "c"]
letters.reverse() # flips the order in place — NOT alphabetical
print(letters) # ['c', 'd', 'a', 'b']
.sort() is a list method that reorders the list in
place and returns nothing. sorted(some_list) is a
built-in function (like len()) that leaves the original
list untouched and hands back a brand-new sorted list instead. Use
sorted() when you still need the original order for
something else.
Two more small but handy methods: .count() tells you how
many times a value shows up, and .index() tells you
where the first one is:
votes = ["yes", "no", "yes", "yes", "no"]
print(votes.count("yes")) # 3
print(votes.index("no")) # 1 — position of the FIRST "no"
Go Deeper: why does .remove() crash on a missing value?
.remove("mouse") raises a ValueError if
"mouse" isn't in the list — Python has no way to
remove something that doesn't exist. Chapter 6 taught you to check
with in before doing something risky; the same habit
applies here: if "mouse" in cart: cart.remove("mouse")
avoids the crash using only what you already know.
.append(),.insert(), and.extend()add items;.remove(),.pop(), and.clear()take them away..sort()and.reverse()reorder a list in place;sorted()returns a new sorted list and leaves the original untouched..count()and.index()ask "how many?" and "where's the first one?" about a value.
3. Tuples: immutable sequences & packing/unpacking
- Tuple = an ordered collection, written with parentheses, that can't be changed.
- Indexing and slicing work the same as lists.
- Unpacking pulls a tuple's values into separate variables in one line.
point = (3, 7). It behaves like a list
for reading — indexing, slicing, len() all work the same
way — but it is immutable: once created, its
contents can never change, the same guarantee strings gave you in
Chapter 6.
point = (3, 7)
print(point[0], point[1]) # 3 7
print(point[-1]) # 7 — negative indexing, same as lists
coords = (10, 20, 30, 40)
print(coords[1:3]) # (20, 30) — slicing works too
Trying to change a tuple in place fails immediately — that's the whole point of choosing a tuple over a list:
point = (3, 7)
point[0] = 9
# TypeError: 'tuple' object does not support item assignment
That crash is a feature, not a limitation. A pair of GPS coordinates,
a database row you just read, or a fixed record like
(year, month, day) shouldn't be editable by accident —
a tuple makes that mistake impossible instead of just unlikely.
Packing and unpacking is the other reason tuples
show up constantly. Packing is just creating one:
point = (3, 7) "packs" two values into one tuple.
Unpacking reverses that — one line assigns each
value inside a tuple to its own variable:
point = (3, 7)
x, y = point # unpacking: x = 3, y = 7
print(x, y) # 3 7
# Unpacking works for any size tuple, as long as the counts match
record = ("Alice", 29, "Engineering")
name, age, dept = record
print(name, age, dept) # Alice 29 Engineering
(5) is just the number 5 in parentheses —
not a tuple. Python needs a trailing comma to know you mean a tuple:
single = (5,). Easy to forget, and a common source of
confusing bugs, so watch for it whenever a tuple has exactly one item.
Go Deeper: why not just use a list for everything?
You could — Python won't stop you. But immutability communicates intent: a tuple tells anyone reading the code "this is a fixed record, don't expect it to change," the same way marking something immutable in any language is a promise about how it will be used. A list, by contrast, signals "this collection is expected to grow, shrink, or reorder." Picking the right one is a small but real piece of writing code other people (including future you) can trust.
- A tuple is written with parentheses; indexing, slicing, and
len()work exactly like lists. - Tuples are immutable —
point[0] = 9raises aTypeError, by design. - Unpacking (
x, y = point) assigns each of a tuple's values to its own variable in one line. - A one-item tuple needs a trailing comma:
(5,), not(5).
4. Nested lists & 2D data
- Nested list = a list whose items are themselves lists.
- Two indexes reach a single value: row, then column.
- A common shape for grids, tables, and rows of records.
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(grid[0]) # [1, 2, 3] — the whole first row
print(grid[1][2]) # 6 — row 1, column 2
grid[0] -> [1, 2, 3]
grid[1] -> [4, 5, 6]
grid[2] -> [7, 8, 9]
grid[1] is the row: [4, 5, 6]
grid[1][2] is that row's item at index 2: 6
The first index picks a row; the second index picks an item inside that row. Mutating a nested list works the same way — reach in with both indexes, then assign:
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
grid[2][0] = 70
print(grid) # [[1, 2, 3], [4, 5, 6], [70, 8, 9]]
A realistic use case: a small classroom roster, where each row holds
one student's name and score. A for loop walks the
outer list, and each student is one inner list:
classroom = [
["Priya", 91],
["Amir", 84],
["Zoe", 77],
]
for student in classroom:
print(student[0], "-", student[1])
# Priya - 91
# Amir - 84
# Zoe - 77
Go Deeper: nesting isn't limited to two levels
A list can hold a list of lists of lists, as deep as the data
actually needs — cube[0][1][2] is perfectly valid
Python. In practice, two levels (rows and columns) cover the huge
majority of real cases; going deeper usually means the data would
be clearer represented some other way, which is exactly the
problem dictionaries (Chapter 8) start to solve.
- A nested list is a list whose items are themselves lists — no special syntax needed.
grid[row][col]reaches a single value: the first index picks the row, the second picks the item inside it.- Looping over a nested list with
for row in grid:gives you one inner list per iteration.
5. Copying lists: shallow copies & the is-vs-== trap
- Assignment (
b = a) doesn't copy a list — it makes a second name for the same list. .copy()ora[:]makes an actual second list.ischecks "same object?";==checks "same contents?"
Chapter 3 introduced is alongside ==, but
the difference barely mattered for numbers and strings. For lists,
it matters a lot — because b = a does not create a new
list.
original = [1, 2, 3]
alias = original # NOT a copy — just a second name for the same list
alias.append(4)
print("original:", original) # [1, 2, 3, 4] — changed too!
print("alias:", alias) # [1, 2, 3, 4]
original ----\
>---- [1, 2, 3, 4]
alias ----/
is and == tell this apart precisely —
is asks "are these literally the same object?" while
== asks "do these have equal contents right now?":
original = [1, 2, 3]
alias = original
print(original is alias) # True — same object
print(original == alias) # True — and, of course, equal contents
copy1 = original.copy() # a real, independent copy
print(original is copy1) # False — a different object
print(original == copy1) # True — but the contents currently match
The fix is to make an actual copy before handing a list to code that
might change it. Two equivalent ways: .copy(), or the
full-range slice trick from Chapter 6, a[:]:
original = [1, 2, 3]
copy1 = original.copy() # option 1
copy2 = original[:] # option 2 — a full slice also makes a real copy
copy1.append(99)
print("original:", original) # [1, 2, 3] — untouched
print("copy1:", copy1) # [1, 2, 3, 99]
print(original is copy2) # False — a separate list
.copy() and a[:] both make a
shallow copy — a new outer list containing the same
items. For a flat list of numbers or strings, that's a completely
independent copy in every way that matters here. (Nested lists, from
Section 4, add a wrinkle a shallow copy doesn't fully solve — that's
a deeper-Python topic for later, and not something this chapter's
examples run into.)
Go Deeper: why does Python work this way?
A variable in Python never "contains" a list directly — it holds a
reference (an address) pointing at the list object sitting in
memory. b = a copies the reference, not the list
itself, which is fast and cheap. It's the same reason two
variables can point at the same string too — but since strings are
immutable, that sharing is invisible; you can never tell the
difference. Lists being mutable is what turns invisible sharing
into a real bug if you're not watching for it.
b = amakesba second name for the same list — mutating one mutates both..copy()ora[:]creates a real, independent second list.ischecks whether two names point at the same object;==checks whether their contents currently match.
6. Real-world lists & tuples in production
- Batch processing means looping over a list of records, one at a time.
- Each record is often a small list or tuple of related fields.
- Filter, accumulate, and report — the same pattern as Chapter 5's accumulator, just on rows now.
A very common real shape: a list of orders, where each order is a
small nested list of [order_id, amount, status]. A
for loop walks every order; an if filters
to the ones that matter; an accumulator (Chapter 5) tracks a running
total:
orders = [
["ORD-1001", 42.50, "shipped"],
["ORD-1002", 15.00, "pending"],
["ORD-1003", 88.25, "shipped"],
["ORD-1004", 5.75, "cancelled"],
]
total_shipped = 0
shipped_count = 0
for order in orders:
order_id = order[0]
amount = order[1]
status = order[2]
if status == "shipped":
total_shipped = total_shipped + amount
shipped_count += 1
print(f"{order_id}: ${amount:.2f} — {status}")
print(f"Shipped orders: {shipped_count}, total revenue: ${total_shipped:.2f}")
Tuples earn their keep here too — a coordinate, unlike an order, shouldn't ever be edited once it's recorded. Warehouses, delivery stops, and map pins are naturally tuples, and unpacking makes them easy to use:
warehouse_a = (40.71, -74.01)
warehouse_b = (34.05, -118.24)
print(f"Warehouse A is at {warehouse_a[0]}, {warehouse_a[1]}")
lat, lon = warehouse_b
print(f"Warehouse B is at {lat}, {lon}")
Go Deeper: why not one list per field instead?
You could keep order_ids = [...],
amounts = [...], and statuses = [...] as
three separate parallel lists, matched up by position. It works,
but it's fragile — sort one list and forget the other two, and
every record silently corrupts. Grouping each record's fields
together (as one row, list, or tuple) keeps everything about a
single order moving as one unit. Chapter 8's dictionaries make
this even clearer by naming each field instead of relying on
position.
- Batch processing loops over a list of records, filtering and accumulating as it goes — the same shape as Chapter 5's accumulator pattern.
- Each record is often a small list (fields that might change) or tuple (fields that shouldn't).
- Keeping a record's fields together avoids the fragility of matching up several separate parallel lists by position.
- Every e-commerce cart, order queue, and to-do app is, underneath, a list being appended to, popped from, and looped over — the exact operations this chapter covers.
- Spreadsheets, image data, and game boards are all commonly represented as nested lists in real code —
grid[row][col]is the same pattern whether it's a tic-tac-toe board or a CSV file loaded into memory. - The aliasing bug from Section 5 is a genuine, common source of production bugs — passing a list around and mutating it unexpectedly has caused real data-corruption incidents; knowing when to reach for
.copy()is a professional habit, not just a classroom exercise.
Points to Remember
- Lists are written with
[...]and are mutable — indexing and slicing work like strings, but items can be overwritten in place. .append(),.insert(),.extend()grow a list;.remove(),.pop(),.clear()shrink it;.sort()/.reverse()reorder it in place, whilesorted()returns a new list.- Tuples are written with
(...)and are immutable — use them for fixed records like coordinates; unpacking (x, y = point) reads a tuple's values into separate variables in one line. - Nested lists (
grid[row][col]) represent 2D data like grids and tables; the first index picks a row, the second picks an item inside it. b = aaliases a list — both names point at the same object, so mutating one mutates both;.copy()ora[:]makes a real, independent copy.ischecks whether two names refer to the same object;==checks whether their contents currently match — these can disagree for lists in a way they never do for simple numbers.- Real-world batch processing loops over a list of records (orders, rows, coordinates), filtering and accumulating — the exact pattern this chapter's capstone walked through.