Lists & Tuples
You'll learn to
- -Create and modify lists with append, pop, insert, remove, and sort
- -Create tuples and explain why they're immutable
- -Unpack a tuple into multiple named variables
- -Decide when a list is the right tool and when a tuple is
Every program you've 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'll make as a Python programmer.
Lists: Ordered and Mutable
A list is an ordered, mutable collection - "mutable" meaning 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 isn't 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're really returning a single tuple, which the caller unpacks. You'll see this pattern constantly.
Choosing Between Them
- -Use a list when the collection will grow, shrink, or get reordered - a queue of tasks, a running list of results.
- -Use a tuple for a small, fixed group of values that belong together and won't change - a coordinate, an RGB triple, a (key, value) pair.
- -As a rule of thumb: if you're about to write .append() or .sort() on it, you wanted a list.
What's the difference between a list and a tuple?
"A tuple uses parentheses and a list uses square brackets."
"The syntax difference is the least important part. A list is mutable - you can append, remove, and reorder its contents after creation - while a tuple is immutable, so once built it can't change. That makes tuples a good fit for small, fixed groupings of values you want to guarantee won't be accidentally mutated later, and it's also why tuples (not lists) can be used as dictionary keys - Python requires dict keys to be hashable, and mutable objects like lists aren't."