Python — Tuples
Creating tuples
Tuples are like lists but immutable — once created, they can't be changed:
colors = ("red", "green", "blue")
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)
single = (42,) # trailing comma needed for single-element tuples
empty = ()
The trailing comma on single-element tuples is required. Without it, (42) is just a parenthesized expression, not a tuple.
Accessing elements
colors = ("red", "green", "blue")
print(colors[0]) # red
print(colors[-1]) # blue
print(colors[0:2]) # ("red", "green") — slicing returns a tuple
Slicing works exactly like lists, but returns a tuple instead of a list.
Tuples are immutable
colors = ("red", "green", "blue")
# colors[0] = "purple" # TypeError: 'tuple' does not support item assignment
You can't modify, add, or remove elements. To "change" a tuple, create a new one:
colors = ("red", "green", "blue")
colors = ("purple",) + colors[1:] # ("purple", "green", "blue")
Tuple operations
a = (1, 2, 3)
b = (4, 5, 6)
# Concatenation
print(a + b) # (1, 2, 3, 4, 5, 6)
# Repetition
print(a * 3) # (1, 2, 3, 1, 2, 3, 1, 2, 3)
# Length
print(len(a)) # 3
# Membership
print(2 in a) # True
# Min, max, sum
print(min(a)) # 1
print(max(a)) # 3
print(sum(a)) # 6
# Count and index
numbers = (1, 2, 2, 3, 3, 3)
print(numbers.count(3)) # 3
print(numbers.index(2)) # 1
Unpacking tuples
Unpacking is where tuples shine:
# Basic unpacking
point = (10, 20)
x, y = point
print(f"x = {x}, y = {y}") # x = 10, y = 20
# Swap values — a Python classic
a = 5
b = 10
a, b = b, a
print(a, b) # 10 5
# Multiple return values
def get_min_max(numbers):
return min(numbers), max(numbers)
low, high = get_min_max([3, 1, 4, 1, 5, 9])
print(f"Min: {low}, Max: {high}") # Min: 1, Max: 9
Tuple vs list
| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable | Mutable |
| Syntax | (1, 2, 3) | [1, 2, 3] |
| Performance | Faster | Slightly slower |
| Dictionary keys | Yes | No |
| Use case | Fixed data | Dynamic collections |
Tuples are faster because Python can optimize immutable data. Use them for fixed structures like coordinates, RGB colors, or database rows.
Named tuples
For more readable tuples, use namedtuple:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x) # 10 — access by name
print(p[0]) # 10 — access by index
print(p) # Point(x=10, y=20)
Named tuples combine tuple performance with readable field access. They're lighter than classes for simple data containers.
Tuples as dictionary keys
Lists can't be dictionary keys because they're mutable. Tuples can:
# Coordinate grid
grid = {
(0, 0): "origin",
(1, 0): "right",
(0, 1): "up"
}
print(grid[(1, 0)]) # right
Iterating over tuples
colors = ("red", "green", "blue")
# Basic iteration
for color in colors:
print(color)
# With index
for i, color in enumerate(colors):
print(f"{i}: {color}")
Tuple comprehensions don't exist
Unlike lists, there's no tuple comprehension syntax. Use tuple() around a generator expression:
# List comprehension
squares_list = [x ** 2 for x in range(5)]
# Tuple from generator
squares_tuple = tuple(x ** 2 for x in range(5))
print(squares_tuple) # (0, 1, 4, 9, 16)
Common patterns
# Return multiple values from a function
def divide(a, b):
if b == 0:
return None
return a // b, a % b # returns a tuple
quotient, remainder = divide(17, 5)
print(f"17 ÷ 5 = {quotient} remainder {remainder}")
# Tuple as a record
person = ("Ada", 36, "Engineer")
name, age, job = person
print(f"{name} is a {age}-year-old {job}")
# Packing
coordinates = 10, 20, 30 # parentheses optional when packing
print(type(coordinates)) # <class 'tuple'>
Tuple packing and unpacking
# Packing — multiple values into a tuple
def get_user():
return "Ada", 36, "ada@example.com"
# Unpacking — tuple into variables
name, age, email = get_user()
print(f"{name} ({age}) - {email}")
# Star unpacking — grab the rest
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]
*head, last = (1, 2, 3, 4, 5)
print(head) # [1, 2, 3, 4]
print(last) # 5
Mini Practice
- Create a tuple of five cities and print the first and last
- Use tuple unpacking to swap two variables
- Write a function that returns a tuple of (min, max, average) from a list
- Create a named tuple for a "Book" with title, author, and pages
- Use a tuple as a dictionary key to store coordinates
Next: sets — unique collections →
Related Topics
Frequently Asked Questions about Tuples
What is Tuples in Python?
Tuples is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Tuples?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Tuples.
Why is Tuples important in Python?
Tuples is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.