Introduction
Python tuples are immutable, ordered sequences that can hold elements of different types. Unlike lists, tuples cannot be modified after creation, which makes them hashable and suitable for use as dictionary keys. Tuples are commonly used for returning multiple values from functions and representing fixed collections of related data.
Key Concepts
- Immutability: Tuples cannot be changed after creation
- Ordered: Elements maintain their order
- Heterogeneous: Can contain different data types
- Hashable: Can be used as dictionary keys (if elements are hashable)
- Packing and unpacking: Assign multiple values at once
- Namedtuples: Type-safe way to access tuple elements
Python Implementation
# Creating tuples
point = (3, 4)
mixed = (1, "hello", 3.14, True)
single = (42,) # Note: comma required for single-element tuple
# Tuple unpacking
x, y = point # x=3, y=4
a, b, c = mixed # Unpack multiple values
first, *rest = [1,2,3,4,5] # first=1, rest=[2,3,4,5]
# Tuple operations
concat = (1, 2) + (3, 4) # (1, 2, 3, 4)
repeat = ("a",) * 3 # ('a', 'a', 'a')
length = len(point) # 2
# Accessing elements
first = point[0] # 3
last = point[-1] # 4
slice_example = point[0:2] # (3, 4)
# Named tuples
from collections import namedtuple
Person = namedtuple("Person", ["name", "age", "city"])
john = Person("John", 30, "NYC")
print(john.name) # John
print(john.age) # 30
# Tuple in dictionary
locations = {(0, 0): "origin", (1, 0): "right", (0, 1): "up"}
When to Use
- Returning multiple values from functions
- Dictionary keys (when immutable required)
- Fixed configuration data
- Coordinate systems and points
- Database records and data rows
- Function arguments and return values
Key Takeaways
- Tuples are immutable, making them hashable and suitable as dictionary keys
- Tuple unpacking provides an elegant way to handle multiple return values
- Namedtuples offer readable, attribute-based access to tuple elements
- Tuples use less memory than lists due to their fixed size
- The immutability guarantees data integrity in fixed collections