Python · Chapter 4 of 21
Python lists and tuples: slicing, copying, comprehensions, zip
14 min study · Examples checked with Python 3.14 and 3.15 ·
A sequence is an ordered collection you can index by position. You have already met two: strings and ranges. This chapter covers the two you will use most for data, lists and tuples, and the operations every sequence shares. The examples follow one small task: cleaning a set of quiz scores and turning them into a ranked report.
Lists, tuples and what they share
A list is written with square brackets and can change after it is created. A tuple uses parentheses (or just commas) and cannot change. Use a list for a collection that grows or shrinks, and a tuple for a fixed group of values that belong together, like a name and a score.
scores = [72, 85, 91, 64]
entry = ("Ada", 85)
single = (85,) # the comma makes the tuple, not the parentheses
empty = []
print(len(scores), min(scores), max(scores), sum(scores)) # 4 64 91 312
print(91 in scores, scores.count(85), scores.index(91)) # True 1 2
print(scores + [70], entry * 2) # [72, 85, 91, 64, 70] ('Ada', 85, 'Ada', 85)
len, min, max, sum, in, count, index, + and * work on any sequence, strings included. index raises a ValueError when the value is missing, so check with in first or catch the error.
Tuples are immutable only one level deep. You cannot replace an element of ("draft", ["intro"]), but you can append to the list inside it. Because a tuple of numbers and strings can never change, it can be used as a dictionary key or stored in a set, which a list cannot (chapter 5).
Indexing and slicing
Positions start at 0. Negative positions count from the end, so -1 is the last item. A slice seq[start:stop:step] takes a range of positions and always returns a new sequence of the same type.
scores = [72, 85, 91, 64, 77]
print(scores[0], scores[-1]) # 72 77
print(scores[1:3]) # [85, 91]
print(scores[:2], scores[3:]) # [72, 85] [64, 77]
print(scores[::2]) # [72, 91, 77]
print(scores[::-1]) # [77, 64, 91, 85, 72]
print(scores[10:]) # []
As with range, the stop position is excluded, which makes seq[:n] and seq[n:] split a sequence cleanly into two parts. A single index outside the list raises IndexError, but a slice past the end simply stops at the end, so scores[10:] is an empty list rather than an error.
Changing a list in place
Lists have methods that modify them directly:
scores = [72, 85, 91]
scores.append(64) # one item at the end
scores.extend([88, 79]) # every item of another iterable
scores.insert(0, 100) # at a position
last = scores.pop() # remove and return the last item
scores.remove(64) # remove the first item equal to 64
scores[1] = 74 # replace by position
del scores[2:4] # delete a slice
print(last, scores) # 79 [100, 74, 88]
The classic mistake is scores.append([88, 79]), which adds one item, a nested list. Another is assigning the result of a method that changes a list in place: append, extend, insert, remove, sort and reverse all return None, so scores = scores.sort() replaces your list with None.
Aliases and copies
Assignment never copies. It binds another name to the same list, and a change through either name is visible through both:
original = [72, 85]
alias = original
copy = original.copy() # or list(original), or original[:]
alias.append(91)
print(original, copy) # [72, 85, 91] [72, 85]
bad_grid = [[0, 0]] * 2 # two references to one inner list
bad_grid[0][0] = 1
good_grid = [[0, 0] for _ in range(2)]
good_grid[0][0] = 1
print(bad_grid, good_grid) # [[1, 0], [1, 0]] [[1, 0], [0, 0]]
copy() makes a shallow copy: a new outer list whose items are the same objects. For a list of numbers that is all you need. For a list of lists, the inner lists are still shared; copy.deepcopy from the standard library copies them too. The grid example shows the same effect from another angle: * repeats a reference, while a comprehension creates a fresh inner list on every pass.
Functions receive references as well, so a function that appends to a list it was given changes the caller’s list. Chapter 7 returns to this.
Build lists with comprehensions
A list comprehension builds a new list from an iterable in one expression. Read it as “this value, for each item, if this condition”:
raw = [72, -1, 85, 101, 91, 64]
valid = [s for s in raw if 0 <= s <= 100]
curved = [min(s + 5, 100) for s in valid]
labels = ["pass" if s >= 75 else "retry" for s in valid]
pairs = [(a, b) for a in "AB" for b in (1, 2)]
print(valid) # [72, 85, 91, 64]
print(curved) # [77, 90, 96, 69]
print(labels) # ['retry', 'pass', 'pass', 'retry']
print(pairs) # [('A', 1), ('A', 2), ('B', 1), ('B', 2)]
An if at the end filters items. An if ... else at the front chooses the value to produce for every item. Several for clauses nest from left to right, like nested loops. Python 3.15 also allows unpacking in a comprehension, so [*row for row in grid] flattens a list of lists.
Comprehensions are for building a value. If you need several statements, error handling or side effects such as printing, write an ordinary loop.
Unpacking and zip
Unpacking assigns the items of a sequence to several names at once, and a starred name collects whatever is left:
first, *middle, last = [72, 85, 91, 64]
print(first, middle, last) # 72 [85, 91] 64
names = ["Ada", "Grace", "Linus"]
scores = [72, 85, 91]
for name, score in zip(names, scores, strict=True):
print(f"{name}: {score}")
print([*names, "Joan"]) # ['Ada', 'Grace', 'Linus', 'Joan']
zip pairs items from several iterables. By default it stops at the shortest one, which silently drops data when one list is accidentally shorter. strict=True raises a ValueError instead. The check happens while the pairs are consumed, not when zip is called. Unpacking also fails loudly when the counts don’t match: a, b = [1, 2, 3] raises a ValueError.
Sorting
sorted returns a new sorted list from any iterable and leaves the original alone. list.sort sorts a list in place and returns None.
from operator import itemgetter
report = [("Ada", 72), ("Grace", 91), ("Linus", 85), ("Joan", 91)]
ranked = sorted(report, key=itemgetter(1), reverse=True)
print(ranked) # [('Grace', 91), ('Joan', 91), ('Linus', 85), ('Ada', 72)]
print(sorted(report, key=lambda row: (-row[1], row[0]))[0]) # ('Grace', 91)
print(sorted(["b", "C", "a"]), sorted(["b", "C", "a"], key=str.casefold))
# ['C', 'a', 'b'] ['a', 'b', 'C']
A key function turns each item into the value used for comparison. itemgetter(1) picks the score; a lambda (chapter 8) can build a tuple to sort by several fields, here score descending and then name. Sorting is stable: items with equal keys keep their original order, which is why Grace stays ahead of Joan. Strings sort by code point, so capitals come before lowercase letters unless you sort with key=str.casefold.
Practice
Start from names = ["Ada", "Grace", "Linus", "Joan"] and scores = [72, 85, 91, 64]. Build a list of (name, score) tuples, keep only scores of 70 or more, sort them by score from highest to lowest, and unpack the top entry into top_name, top_score. Then delete the last score and run your code again.
Answer check: the top entry is ("Linus", 91), and the filtered list has three entries. With one score missing, zip(..., strict=True) raises ValueError instead of quietly dropping Joan. The original lists are unchanged throughout if you only use sorted and comprehensions.
Summary
Lists change, tuples don’t, and both support indexing, slicing and the common sequence functions. Slices copy and never fail on bounds; single indices do. Assignment creates aliases, copy() is shallow, and comprehensions build new lists. Use zip(..., strict=True) when sequences must line up, and sorted with a key when you need a new ordering.