11.14 Best Practices
When to reach for a tuple over a list, using unpacking to make multi-value returns and record access self-documenting, and a quick decision table for choosing between the two.
When to Use Tuples
- The data represents a fixed record (coordinates, RGB values, a database row).
- The value needs to be a dict key or set member.
- The intent is to signal to readers that this collection should never change.
Efficient Coding
Use tuple unpacking to make multi-value returns and record access self-documenting, instead of indexing into an unnamed sequence.
# Less readable
server = ("web01", "10.0.1.5", "running")
print(server[0], server[2])
# More readable -- unpack into named variables
name, ip, status = server
print(name, status)
Choosing Tuple vs. List
| Situation | Best choice |
|---|---|
| Fixed record that shouldn’t change | tuple |
| Collection that will grow/shrink/reorder | list |
| Needs to be a dict key or set member | tuple |
| Returning multiple values from a function | tuple |
Quick Interview Answer
“The decision between tuple and list almost always comes down to one question: does this collection’s size or contents ever need to change after creation? If not — a coordinate, an RGB value, a config record, a function’s multi-value return — a tuple is the right default, both for the small performance win and, more importantly, because it documents that intent to every future reader. The other habit worth building is unpacking over indexing:
name, ip, status = serverreads at a glance;server[0],server[2]scattered through a codebase doesn’t, and breaks silently if the tuple’s shape ever changes.”
Common Mistakes
- Defaulting to a list everywhere out of habit, even for data that’s structurally a fixed record and never mutates.
- Indexing into a tuple positionally throughout a codebase instead of unpacking once into named variables at the point of receipt.
- Choosing a tuple for a collection that actually does need to grow later, then working around the immutability with awkward
t = t + (x,)patterns instead of just using a list from the start.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form