Lists & Tuples
You'll learn to
- -Create and modify lists with append, pop, insert, remove, and sort
- -Create tuples and explain why they are immutable
- -Unpack a tuple into multiple named variables
- -Decide when a list is the right tool and when a tuple is
Every program you have written so far has dealt with one value at a time. Real problems usually involve a collection of values: a list of scores, a set of usernames, a lookup table of prices. Python's two most common ordered collections are the list and the tuple, and the difference between them is one of the first genuinely important design decisions you will make as a Python programmer.
Lists: Ordered and Mutable
A list is an ordered, mutable collection. Mutable means you can change it after creating it: add items, remove items, reorder them, all without creating a new list. append() adds to the end (the most common operation), pop() removes and returns the last item (or a specific index if you pass one), insert() places an item at a specific position, remove() deletes the first item matching a value, and sort() reorders the list in place.
Tuples: Ordered and Immutable
A tuple looks almost identical to a list, but once created, it cannot be changed. No append, no item assignment, nothing. That immutable property is not a limitation so much as a signal: a tuple communicates "this is a fixed, small bundle of related values that should never change," like a coordinate pair or an RGB color.
Tuple Unpacking
Unpacking lets you assign each element of a tuple to its own variable in one line: x, y = point instead of x = point[0] and y = point[1]. This is exactly how Python functions return "multiple values." They are really returning a single tuple, which the caller unpacks. You will see this pattern constantly.
Choosing Between Them
- -Use a list when the collection will grow, shrink, or get reordered, like a queue of tasks or a running list of results.
- -Use a tuple for a small, fixed group of values that belong together and won't change, like a coordinate, an RGB triple, or a (key, value) pair.
- -As a rule of thumb: if you are about to write .append() or .sort() on it, you wanted a list.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.