What is a Tuple?
A tuple is an ordered, immutable collection of items. Once created, you cannot modify, add, or remove items. Tuples are faster than lists and can be used as dictionary keys.
Creating Tuples
Create tuples using parentheses:
# Empty tuple
empty = ()
# Tuple with items
coordinates = (10, 20)
colors = ("red", "green", "blue")
# Single item tuple (note the comma!)
single = (42,) # Comma is required!
not_tuple = (42) # This is just an integer
# Without parentheses (tuple packing)
point = 10, 20, 30 # (10, 20, 30)
# Using tuple() constructor
numbers = tuple([1, 2, 3]) # (1, 2, 3)
Accessing Elements
Access elements like lists:
point = (10, 20, 30)
print(point[0]) # 10 (first element)
print(point[1]) # 20 (second element)
print(point[-1]) # 30 (last element)
# Slicing
print(point[0:2]) # (10, 20)
Tuple Immutability
Tuples cannot be modified after creation:
point = (10, 20)
# These will cause errors:
# point[0] = 5 # TypeError!
# point.append(30) # AttributeError!
# del point[0] # TypeError!
# But you can create new tuples
new_point = point + (30,) # (10, 20, 30)
multiplied = point * 2 # (10, 20, 10, 20)
Tuple Unpacking
Assign tuple values to variables:
point = (10, 20)
# Unpacking
x, y = point
print(x) # 10
print(y) # 20
# Multiple assignment
a, b, c = (1, 2, 3)
# Swap variables (elegant!)
a, b = b, a
# Unpack with * (Python 3)
first, *rest = (1, 2, 3, 4, 5)
# first = 1, rest = [2, 3, 4, 5]
Tuple Methods
Tuples have limited methods (since they're immutable):
colors = ("red", "green", "blue", "red")
# Count occurrences
count = colors.count("red") # 2
# Find index
index = colors.index("green") # 1
# Get length
length = len(colors) # 4
When to Use Tuples
- Fixed data: When data shouldn't change (coordinates, RGB values)
- Dictionary keys: Tuples can be keys, lists cannot
- Multiple return values: Functions can return tuples
- Performance: Faster than lists for iteration
- Data integrity: Prevent accidental modification
Common Patterns
Returning Multiple Values
def get_name_age():
return "Alice", 25 # Returns tuple
name, age = get_name_age() # Unpacking
Using as Dictionary Keys
# Tuples can be keys
locations = {
(0, 0): "Origin",
(1, 1): "Corner",
(2, 2): "Diagonal"
}
print(locations[(1, 1)]) # "Corner"
Named Tuples
from collections import namedtuple
# Create a named tuple type
Point = namedtuple('Point', ['x', 'y'])
# Create instances
p1 = Point(10, 20)
p2 = Point(x=30, y=40)
# Access by name
print(p1.x) # 10
print(p1.y) # 20
Tuples vs Lists
| Feature | Tuple | List |
|---|---|---|
| Mutable | No | Yes |
| Syntax | () | [] |
| Dictionary Key | Yes | No |
| Performance | Faster | Slower |
| Methods | Few (count, index) | Many |
Best Practices
- Use tuples for fixed data: Coordinates, constants, configuration
- Use lists for dynamic data: When you need to add/remove items
- Remember the comma: Single-item tuples need a trailing comma
- Use named tuples: For better readability when appropriate
Next Steps
Compare with lists to understand when to use each, or learn about sets for unique collections.