🐍 Python for Everyone

← Back to all chapters

Chapter 7 of 27 Beginner 28 min read

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

A shopping cart, a class roster, a set of GPS coordinates, a batch of orders waiting to ship — every one of these is just a collection of values that a program needs to hold, loop over, and change. Lists (and their unchangeable cousin, tuples) are Python's everyday tools for exactly that job.
Sub-topic 1 of 6

1. Creating lists & accessing elements

At a glance
  • 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.
Think in positions: a list is a row of boxes, and each box has a number — same idea as string indexing.
What is... a list? A list is an ordered, changeable collection of values, written between square brackets and separated by commas: 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.
creating_lists.py
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:

Index map for a 5-item list
apple  banana  cherry  date  elderberry
[0]    [1]     [2]     [3]   [4]
[-5]   [-4]    [-3]    [-2]  [-1]
indexing_slicing_lists.py
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.

What is... mutability? Mutable means "changeable in place." Strings are immutable (Chapter 6) — 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.
mutating_a_list.py
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
fruits[1] = "blueberry"   # overwrite one item in place
print(fruits)   # ['apple', 'blueberry', 'cherry', 'date', 'elderberry']
try_lists.py
Click "Run Code" — try changing an index or slice.
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.

Quick recap
  • A list is written with square brackets: [item1, item2, ...], and len() 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.
Sub-topic 2 of 6

2. List methods that grow, shrink, and reorder a list

At a glance
  • Grow a list with .append(), .insert(), .extend().
  • Shrink it with .remove(), .pop(), .clear().
  • Reorder it with .sort(), sorted(), .reverse().
Use this when: a shopping cart, a queue, or a leaderboard needs to change over time.

Three methods add new items to a list, each in a slightly different spot:

growing_a_list.py
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']
What is... the difference between .append() and .extend()? .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:

shrinking_a_list.py
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:

reordering_a_list.py
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']
What is... the difference between .sort() and sorted()? .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:

counting_and_finding.py
votes = ["yes", "no", "yes", "yes", "no"]
print(votes.count("yes"))   # 3
print(votes.index("no"))    # 1 — position of the FIRST "no"
try_list_methods.py
Click "Run Code" — try adding or removing different names.
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.

Quick recap
  • .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.
Sub-topic 3 of 6

3. Tuples: immutable sequences & packing/unpacking

At a glance
  • 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.
Use this when: a value is a fixed record that should never accidentally change — a coordinate, a database row, a fixed-size point in time.
What is... a tuple? A tuple is an ordered collection written with parentheses instead of square brackets: 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.
tuple_basics.py
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:

tuples_cannot_change.py
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:

packing_unpacking.py
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
What is... a one-item tuple? (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.
try_tuples.py
Click "Run Code" — try unpacking a tuple of your own.
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.

Quick recap
  • A tuple is written with parentheses; indexing, slicing, and len() work exactly like lists.
  • Tuples are immutable — point[0] = 9 raises a TypeError, 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).
Sub-topic 4 of 6

4. Nested lists & 2D data

At a glance
  • 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.
Use this when: data naturally has rows and columns — a spreadsheet, a tic-tac-toe board, a table of student scores.
What is... a nested list? A nested list is simply a list where each item is itself a list — Python doesn't need any new syntax for this, since a list can hold any type of value, including another list. This is how Python represents "2D" data: rows and columns.
nested_lists.py
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
Reading grid[1][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:

mutating_nested_lists.py
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_roster.py
classroom = [
    ["Priya", 91],
    ["Amir", 84],
    ["Zoe", 77],
]

for student in classroom:
    print(student[0], "-", student[1])
# Priya - 91
# Amir - 84
# Zoe - 77
try_nested_lists.py
Click "Run Code" — try changing a square with board[row][col] = "X".
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.

Quick recap
  • 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.
Sub-topic 5 of 6

5. Copying lists: shallow copies & the is-vs-== trap

At a glance
  • Assignment (b = a) doesn't copy a list — it makes a second name for the same list.
  • .copy() or a[:] makes an actual second list.
  • is checks "same object?"; == checks "same contents?"
Key idea: two variable names can secretly point at the exact same list.

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.

the_aliasing_bug.py
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]
Two names, one list
original ----\
              >---- [1, 2, 3, 4]
alias    ----/
What is... aliasing? Aliasing is when two variable names refer to the exact same list object in memory, instead of two separate lists that happen to look alike. Changing the list through either name changes what both names see — there's really only one list, wearing two labels.

is and == tell this apart precisely — is asks "are these literally the same object?" while == asks "do these have equal contents right now?":

is_vs_equals.py
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[:]:

fixing_the_aliasing_bug.py
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
What is... a shallow copy? .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.)
try_copying.py
Click "Run Code" — try backup = team instead of .copy() and see what changes.
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.

Quick recap
  • b = a makes b a second name for the same list — mutating one mutates both.
  • .copy() or a[:] creates a real, independent second list.
  • is checks whether two names point at the same object; == checks whether their contents currently match.
Sub-topic 6 of 6

6. Real-world lists & tuples in production

At a glance
  • 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.
Pattern to remember: loop the batch, filter what matters, accumulate a total, then report.

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:

order_report.py
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:

tracking_coordinates.py
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}")
What is... a record? A record is one complete "row" of related data treated as a single unit — one order, one student, one coordinate. Whether you represent a record as a small list or a tuple is a real design choice: use a tuple when the fields shouldn't change once created (a coordinate), and a list when they might (an order whose status updates over time).
try_order_report.py
Click "Run Code" — try adding another order to the list.
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.

Quick recap
  • 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.
In the Real World

Points to Remember

← All Chapters Take the Quiz →