Python Tuples
Tuples are ordered, immutable sequences in Python. Once created, their elements cannot be changed, added, or removed. They are perfect for representing fixed collections of data.
Creating Tuples
python
# With parentheses
point = (3, 4)
colors = ("red", "green", "blue")
mixed = (1, "hello", 3.14, True)
# Without parentheses (tuple packing)
coordinates = 10, 20, 30
# Single element tuple (comma is required!)
single = (42,) # This is a tuple
not_tuple = (42) # This is just an integer!
print(type(single)) # <class 'tuple'>
print(type(not_tuple)) # <class 'int'>
# Empty tuple
empty = ()
empty = tuple()
# From other iterables
from_list = tuple([1, 2, 3])
from_string = tuple("Python") # ('P', 'y', 't', 'h', 'o', 'n')
from_range = tuple(range(5)) # (0, 1, 2, 3, 4)Accessing Elements
python
fruits = ("apple", "banana", "cherry", "date", "elderberry")
# Indexing
print(fruits[0]) # apple
print(fruits[-1]) # elderberry
# Slicing
print(fruits[1:3]) # ('banana', 'cherry')
print(fruits[:3]) # ('apple', 'banana', 'cherry')
print(fruits[::2]) # ('apple', 'cherry', 'elderberry')Tuple Immutability
python
point = (3, 4)
# Cannot modify elements
# point[0] = 10 # TypeError: 'tuple' object does not support item assignment
# Cannot add or remove elements
# point.append(5) # AttributeError
# But you can create a new tuple
point = point + (5,)
print(point) # (3, 4, 5)
# Tuples containing mutable objects
data = ([1, 2], [3, 4])
data[0].append(99) # The list inside CAN be modified
print(data) # ([1, 2, 99], [3, 4])
# But you can't replace the list itself:
# data[0] = [5, 6] # TypeErrorTuple Unpacking
python
# Basic unpacking
point = (3, 4)
x, y = point
print(f"x={x}, y={y}") # x=3, y=4
# Swap variables
a, b = 10, 20
a, b = b, a
print(a, b) # 20 10
# Ignore values with _
name, _, age = ("Alice", "ignored", 30)
print(name, age) # Alice 30
# Extended unpacking with *
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5] (note: returns a list)
first, *middle, last = (1, 2, 3, 4, 5)
print(middle) # [2, 3, 4]
# Unpacking in loops
students = [("Alice", 90), ("Bob", 85), ("Charlie", 92)]
for name, score in students:
print(f"{name}: {score}")Tuple Methods and Operations
python
numbers = (1, 2, 3, 2, 4, 2, 5)
# count() - count occurrences
print(numbers.count(2)) # 3
# index() - find first occurrence
print(numbers.index(2)) # 1
print(numbers.index(2, 2)) # 3 (search from index 2)
# Length
print(len(numbers)) # 7
# Membership
print(3 in numbers) # True
print(10 not in numbers) # True
# Min, max, sum
print(min(numbers)) # 1
print(max(numbers)) # 5
print(sum(numbers)) # 19
# Concatenation and repetition
a = (1, 2)
b = (3, 4)
print(a + b) # (1, 2, 3, 4)
print(a * 3) # (1, 2, 1, 2, 1, 2)
# Sorted (returns a list)
unsorted = (3, 1, 4, 1, 5, 9)
print(sorted(unsorted)) # [1, 1, 3, 4, 5, 9]
print(tuple(sorted(unsorted))) # (1, 1, 3, 4, 5, 9)Named Tuples
Named tuples give meaningful names to tuple positions:
python
from collections import namedtuple
# Define a named tuple type
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x) # 3
print(p.y) # 4
print(p[0]) # 3 (index still works)
print(p) # Point(x=3, y=4)
# With more fields
Student = namedtuple("Student", "name age grade")
s = Student("Alice", 25, "A")
print(f"{s.name} got grade {s.grade}") # Alice got grade A
# Convert to dict
print(s._asdict()) # {'name': 'Alice', 'age': 25, 'grade': 'A'}
# Create from dict
data = {"name": "Bob", "age": 30, "grade": "B"}
s2 = Student(**data)
print(s2) # Student(name='Bob', age=30, grade='B')
# Replace values (creates new tuple)
s3 = s._replace(grade="A+")
print(s3) # Student(name='Alice', age=25, grade='A+')Tuples vs Lists
| Feature | Tuple | List |
|---|---|---|
| Syntax | (1, 2, 3) | [1, 2, 3] |
| Mutability | Immutable | Mutable |
| Performance | Faster | Slower |
| Memory | Less | More |
| Hashable | Yes (if elements are) | No |
| Use as dict key | Yes | No |
| Methods | 2 (count, index) | 11+ |
python
import sys
# Memory comparison
t = (1, 2, 3, 4, 5)
l = [1, 2, 3, 4, 5]
print(sys.getsizeof(t)) # 80 bytes
print(sys.getsizeof(l)) # 120 bytes
# Tuples can be dictionary keys
locations = {
(40.7128, -74.0060): "New York",
(51.5074, -0.1278): "London",
(35.6762, 139.6503): "Tokyo",
}
print(locations[(40.7128, -74.0060)]) # New YorkWhen to Use Tuples
python
# 1. Function return values
def get_dimensions():
return (1920, 1080)
width, height = get_dimensions()
# 2. Dictionary keys (must be hashable)
grid = {}
grid[(0, 0)] = "start"
grid[(3, 4)] = "end"
# 3. Fixed configuration data
RGB_RED = (255, 0, 0)
RGB_GREEN = (0, 255, 0)
DATABASE_CONFIG = ("localhost", 5432, "mydb")
# 4. Protecting data from accidental modification
DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
# 5. Storing records
records = [
("Alice", "Engineering", 85000),
("Bob", "Marketing", 72000),
("Charlie", "Engineering", 92000),
]
# Filter and sort
engineering = [r for r in records if r[1] == "Engineering"]
by_salary = sorted(engineering, key=lambda r: r[2], reverse=True)
for name, dept, salary in by_salary:
print(f"{name}: ${salary:,}")Summary
- Tuples are ordered, immutable sequences created with
()or comma separation - Single-element tuples need a trailing comma:
(42,) - Tuples support indexing, slicing, and unpacking
- Only 2 methods:
count()andindex() - Faster and use less memory than lists
- Can be used as dictionary keys (hashable)
- Use named tuples for readable tuple access with named fields
- Use tuples for fixed collections, function return values, and dictionary keys
Next, we'll learn about Python dictionaries.