Python Tuples
Tuple Fundamentals
Tuples are immutable sequences in Python that act as fixed collections of items. They are useful when data should not change after creation.
Key characteristics:
- **Immutable**: Elements cannot be modified, added, or removed
- **Ordered**: Preserve insertion order
- **Heterogeneous**: Can contain different data types
- **Hashable**: Usable as dictionary keys if all elements are hashable
- **Memory Efficient**: Use less memory than lists of the same size
- **Fixed-Length**: Often represent structured data with positional meaning
# Tuple creation examples
empty_tuple = ()
single_elem = (42,) # Single-element tuple requires comma
coordinates = 10.5, -72.3 # Parentheses optional
person = ('John', 32, 'Engineer', True)
matrix = ((1, 2), (3, 4)) # Nested tuples
# Tuple unpacking
name, age, occupation, is_active = person
# Variables assigned: John, 32, Engineer, True
Memory and Performance
Tuples are lightweight compared to lists due to immutability:
- **Fixed Allocation**: Tuples allocate exact memory needed
- **No Overallocation**: Lists over-allocate for growth, tuples don’t
- **Efficient Iteration**: Tuples iterate slightly faster
- **Literal Optimization**: Tuple literals may be folded at compile time
import sys
from timeit import timeit
lst = [1, 2, 3, 4, 5]
tpl = (1, 2, 3, 4, 5)
print(f"List size: {sys.getsizeof(lst)} bytes")
print(f"Tuple size: {sys.getsizeof(tpl)} bytes")
print("List literal:", timeit('[1,2,3,4,5]', number=1000000))
print("Tuple literal:", timeit('(1,2,3,4,5)', number=1000000))
List size: 96 bytes Tuple size: 80 bytes List literal: 0.12 sec Tuple literal: 0.04 sec
Advanced Tuple Patterns
Tuples support powerful usage patterns:
- **Multiple Return Values**: Functions can return multiple results as tuples
- **Data Records**: Represent rows or structured records
- **Dictionary Keys**: Tuples can serve as composite keys
- **Argument Unpacking**: The * operator unpacks tuples into arguments
- **Value Swapping**: Clean, Pythonic variable swapping
# Function returning multiple values
def get_stats(data):
return min(data), max(data), sum(data)/len(data)
# Tuples as dictionary keys
locations = {}
locations[(40.7128, -74.0060)] = "New York"
# Argument unpacking
def vector_length(x, y, z):
return (x**2 + y**2 + z**2)**0.5
point = (3, 4, 5)
print(vector_length(*point)) # 7.071...
# Swapping values
a, b = 10, 20
a, b = b, a
7.0710678118654755
Real-world Applications
Use Case | Example | Benefits |
---|---|---|
Configuration | DIMENSIONS = (1920, 1080) | Immutable fixed settings |
Database Records | row = (1, 'John', '1990-01-01') | Predictable structure |
Coordinates | point = (x, y, z) | Natural representation |
Function Arguments | args = (2, True, 'default') | Convenient unpacking |
Version Numbers | version = (3, 9, 1) | Supports comparisons |