Overview
Tuples are immutable sequences in Python. Once created, their elements cannot be changed, added, or removed. This immutability makes them hashable and suitable as dictionary keys or set elements.
Creating Tuples
# Empty tuple
empty = ()
empty = tuple()
# Single element tuple (note the comma)
single = (1,) # The comma is crucial
not_tuple = (1) # This is just integer 1
# Multiple elements
numbers = (1, 2, 3, 4, 5)
mixed = (1, 'hello', 3.14, True)
# Without parentheses (tuple packing)
coordinates = 10, 20, 30
# From other sequences
from_list = tuple([1, 2, 3])
from_string = tuple('hello') # ('h', 'e', 'l', 'l', 'o')
# Nested tuples
nested = ((1, 2), (3, 4), (5, 6))
Accessing Elements
fruits = ('apple', 'banana', 'cherry', 'date')
# Indexing
first = fruits[0] # 'apple'
last = fruits[-1] # 'date'
# Slicing (returns new tuple)
subset = fruits[1:3] # ('banana', 'cherry')
first_two = fruits[:2] # ('apple', 'banana')
last_two = fruits[-2:] # ('cherry', 'date')
# Step slicing
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
evens = numbers[::2] # (0, 2, 4, 6, 8)
reversed = numbers[::-1] # (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
Tuple Operations
Basic Operations
t1 = (1, 2, 3)
t2 = (4, 5, 6)
# Concatenation
combined = t1 + t2 # (1, 2, 3, 4, 5, 6)
# Repetition
repeated = t1 * 3 # (1, 2, 3, 1, 2, 3, 1, 2, 3)
# Membership testing
if 2 in t1:
print("Found")
# Length
length = len(t1) # 3
Tuple Methods
numbers = (1, 2, 3, 2, 4, 2, 5)
# Count occurrences
count = numbers.count(2) # 3
# Find index
index = numbers.index(4) # 4 (index of first occurrence)
# Find with start/end
index = numbers.index(2, 2) # 3 (search from index 2)
Tuple Unpacking
Basic Unpacking
# Simple unpacking
point = (10, 20)
x, y = point # x=10, y=20
# Multiple assignment
a, b, c = 1, 2, 3 # Actually unpacking a tuple
# Swapping variables
a, b = b, a # Elegant swap using tuple unpacking
Extended Unpacking
# With asterisk operator (Python 3+)
numbers = (1, 2, 3, 4, 5)
first, *rest = numbers # first=1, rest=[2, 3, 4, 5] (rest is a list)
first, *middle, last = numbers # first=1, middle=[2, 3, 4], last=5
# Ignoring values
x, _, z = (1, 2, 3) # x=1, z=3, middle value ignored
# Multiple ignored values
first, *_, last = (1, 2, 3, 4, 5) # first=1, last=5
Named Tuples
from collections import namedtuple
# Define a named tuple class
Point = namedtuple('Point', ['x', 'y'])
Person = namedtuple('Person', 'name age city') # Space-separated string
# Create instances
p = Point(10, 20)
person = Person('John', 30, 'NYC')
# Access by name or index
print(p.x) # 10
print(p[0]) # 10
# Convert to dictionary
person_dict = person._asdict() # {'name': 'John', 'age': 30, 'city': 'NYC'}
# Create from dictionary
data = {'x': 100, 'y': 200}
point = Point(**data)
# Replace values (returns new tuple)
new_person = person._replace(age=31)
Advanced Patterns
Function Returns
def get_min_max(numbers):
return min(numbers), max(numbers)
minimum, maximum = get_min_max([1, 2, 3, 4, 5])
# Multiple return values
def process_data(data):
total = sum(data)
average = total / len(data)
count = len(data)
return total, average, count
total, avg, count = process_data([1, 2, 3, 4, 5])
Tuple as Dictionary Key
# Tuples can be dictionary keys (immutable)
locations = {
(0, 0): 'origin',
(1, 0): 'east',
(0, 1): 'north',
(-1, 0): 'west'
}
position = (1, 0)
direction = locations[position] # 'east'
Argument Unpacking
def calculate(a, b, c):
return a + b * c
args = (2, 3, 4)
result = calculate(*args) # Same as calculate(2, 3, 4)
# With zip
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*pairs) # (1, 2, 3), ('a', 'b', 'c')
Comparison with Lists
| Feature | Tuple | List | |---------|-------|------| | Mutable | No | Yes | | Syntax | () | [] | | Performance | Faster | Slower | | Memory | Less | More | | Use as dict key | Yes | No | | Use in set | Yes | No |
Performance Characteristics
- Access by index: O(1)
- Search: O(n)
- Count: O(n)
- Copy: O(n)
- Memory: Less than lists
- Creation: Faster than lists
Best Practices
1. Use tuples for fixed collections of values 2. Use tuples for function returns with multiple values 3. Prefer named tuples for better code readability 4. Use tuples as dictionary keys when needed 5. Use tuple unpacking for cleaner code 6. Remember the comma for single-element tuples
Common Use Cases
- Function return values
- Dictionary keys (coordinates, multi-part keys)
- Data that shouldn't change (configuration)
- Argument passing
- Database records
- Representing fixed structures
Immutability Gotchas
# Tuples are immutable, but contained objects might not be
t = ([1, 2], [3, 4])
# t[0] = [5, 6] # This would raise TypeError
t[0].append(3) # This works! t is now ([1, 2, 3], [3, 4])
# Be careful with mutable objects in tuples
# Such tuples cannot be used as dict keys or set elements