What are Tuples?
A tuple is an immutable collection. It's essentially a list that cannot be changed after creation. This makes them faster and safer for data that shouldn't be modified, like records or fixed configurations.
python
Creating Tuples
Wait! Creating a tuple with a single item requires a trailing comma. Otherwise, Python treats it as an expression in parentheses.
python
Tuple Unpacking
This is a powerful Python feature for extracting tuple values into variables in one line.
python
Immutable but not entirely?
While the tuple itself can't be changed, it can contain mutable items like lists. Modifying the list inside the tuple is allowed.
python
Named Tuples (collections)
Classic tuples access data by index (e.g.,
user[0]), which isn't very descriptive. Named tuples allow you to assign names to each position, similar to a simple class or a C struct.python
Python 3.7+ Typed Alternative: Usetyping.NamedTuplefor class-based syntax with type hints.python
Why Use Tuples Instead of Lists?
- Performance: Faster to iterate and construct.
- Safety: Prevents accidental data alteration.
- Dictionary Keys: Only immutable objects (like tuples) can be used as keys in a Python dictionary.
Summary
| Feature | Description |
|---|---|
| Immutability | Constant size and content |
| Unpacking | Store values into multiple variables |
| Trailing Comma | Required for single-item tuples |
| NamedTuple | Self-documenting records |
| Best For | Data records, fixed data structures |