5 Lists, tuples, and sets
This chapter introduces Python’s core collection types for everyday work: lists, tuples, and sets. It emphasizes lists as flexible, dynamically sized, heterogeneous sequences, then contrasts them with immutable tuples and membership-focused sets. The narrative centers on mastering indexing, slicing, modification, sorting, and the semantics of copying—knowledge that underpins idiomatic Python—before closing with a hands-on lab and a brief reflection on using AI code generation responsibly.
Lists receive the most attention: creating and sizing them on the fly; mixing element types; using zero-based and negative indices; and slicing (with open-ended bounds) for extraction and copying. You learn to change content via index and slice assignment, and to use common methods—append, extend, insert, del, remove, reverse—plus operators and functions such as in/not in, +, *, min, max, index, count, and sum. Sorting is covered in depth: in-place sort versus the sorted() function, custom key functions (including lambdas), reverse ordering, and the caveat that elements must be comparable. The chapter also explores nested lists (for matrix-like data), highlighting shallow versus deep copies and when to use copy.deepcopy to avoid aliasing pitfalls.
Tuples are presented as list-like but immutable sequences suited to fixed records and as safe dictionary keys; topics include construction, one-element tuple syntax (trailing comma), packing/unpacking (including extended iterable unpacking), and list–tuple conversion. Sets round out the chapter as unordered collections of unique, hashable items, with operations for membership, addition/removal, union, intersection, and symmetric difference, plus frozenset for immutable sets that can themselves be set members. The lab exercise applies these tools to real data—finding extrema, averages, medians, and unique values—while encouraging careful evaluation of AI-generated solutions.
A list with its first item referring to a nested list
The first item of the original list is still a nested list, but the nested variable refers to a different list.
A shallow copy doesn’t copy nested lists.
The code generation prompt in Colaboratory.
Summary
- Lists and tuples are structures that embody the idea of a sequence of elements, as are strings.
- Lists are like arrays in other languages, but with automatic resizing, slice notation, and many convenience functions.
- Tuples are like lists but can’t be modified, so they use less memory and can be dictionary keys (see chapter 7).
- Sets are iterable collections, but they’re unordered and can’t have duplicate elements. Frozen sets are sets that can’t be modified.
- AI tools can generate useful code, but it’s important evaluate that code in light of both the problem and how Python works.
FAQ
How are Python lists different from arrays in other languages?
Lists are dynamic, grow and shrink automatically, and can hold elements of any type (even mixed types and other lists). Example:[2, "two", [1, 2, 3]]. The built-in len() returns the number of top-level elements.How do list indices and slicing work (including negative indices)?
- Indices are 0-based:x[0] is the first item.- Negative indices count from the end:
x[-1] is the last item.- Slices are half-open:
x[i:j] includes i up to but not j.- Omitting bounds:
x[:j] from start, x[i:] to end, x[:] makes a (shallow) copy.- If start is “after” stop (e.g.,
x[-1:2]), the slice is empty.What’s the difference between append, extend, and insert when modifying lists?
-append(obj) adds one element to the end; appending a list nests it: [1,2].append([3,4]) → [1,2,[3,4]].-
extend(iterable) adds each element of the iterable: [1,2].extend([3,4]) → [1,2,3,4].-
insert(i, obj) inserts just before index i (supports negative indices).- Slice assignment also inserts/replaces:
x[i:j] = listb (can change length). Appending via slice: x[len(x):] = [new, items].How do I remove items from a list: del vs remove()?
-del x[i] deletes by position; del x[i:j] deletes a slice.-
x.remove(value) deletes the first matching value; raises ValueError if not found—check first with if value in x:.- Conceptually,
del x[n] ~ x[n:n+1] = [], and del x[m:n] ~ x[m:n] = [].How do I sort a list, and what’s the difference between sort() and sorted()?
-x.sort() sorts the list in place.-
sorted(iterable) returns a new sorted list, leaving the original unchanged.- Both accept
key= (e.g., key=len) and reverse=True.- Mixed incomparable types (e.g., ints and strs together) raise
TypeError.- Lists of lists sort lexicographically (first element, then second, etc.).
What other common list operations should I know?
- Membership:in, not in → booleans.- Concatenate:
a + b returns a new list; replication: a * n repeats elements.- Extremes:
min(x), max(x) (fail if elements aren’t comparable).- Find position:
x.index(value) (raises ValueError if missing).- Count matches:
x.count(value) returns how many times value appears.What’s the difference between a shallow and deep copy of a list (especially with nested lists)?
- Shallow copies (e.g.,x[:], x + [], x * 1) duplicate the outer list but share the same nested objects; changes inside nested items affect both.- Deep copies (
copy.deepcopy(x)) recursively copy nested objects so changes don’t leak between copies.What are tuples, and how do they differ from lists?
Tuples are immutable sequences. You can read (index, slice, iterate) but cannot modify them. Create with parentheses:x = ('a','b','c'). One-element tuples need a trailing comma: (7,). You can concatenate and multiply tuples, and convert with list()/tuple(). Tuples containing mutable objects shouldn’t be used as dictionary keys.How do packing, unpacking, and the starred expression work?
- Multiple assignment packs/unpacks tuples automatically:a, b = 1, 2; swap: a, b = b, a.- Extended unpacking uses
* to collect the “rest” into a list: a, *mid, z = (1,2,3,4) gives a=1, mid=[2,3], z=4. Works with lists and tuples.What are sets and frozensets, and which operations do they support?
- Sets are unordered collections of unique, hashable elements. Create withset(iterable); duplicates are removed.- Modify with
add and remove; check membership with in.- Set algebra: union
|, intersection &, symmetric difference ^.-
frozenset is an immutable set (hashable), so it can be an element of a set; you can’t add/remove from a frozenset.How can I safely copy or convert between lists, tuples, and even strings?
- Copy a list shallowly withx[:]; deep copy nested structures with copy.deepcopy(x).- Convert tuple→list:
list(t); list→tuple: tuple(lst).- Break a string into characters with
list("Hello") → ['H','e','l','l','o'].
The Quick Python Book, Fourth Edition ebook for free