🕯️ Magic Note
The word “tuple” comes from mathematical terms like “quintuple” (five), “sextuple” (six), “n-tuple” (any number). A tuple is simply a fixed-length sequence. Python tuples are immutable, which makes them faster than lists and safe to use as dictionary keys.
Python
# Empty tuple
empty = ()
# Tuple with parentheses
colors = (“red”, “green”, “blue”)
# Tuple without parentheses (tuple packing)
coordinates = 10, 20, 30
print(coordinates) # (10, 20, 30)
# Single item tuple (needs a trailing comma)
single = (5,)
not_a_tuple = (5) # This is just the integer 5, not a tuple
# Mixed types
mixed = (42, “hello”, 3.14, True)
# Nested tuples
nested = ((1, 2), (3, 4), (5, 6))
# Using the tuple() constructor
from_list = tuple([1, 2, 3]) # (1, 2, 3)
from_string = tuple(“abc”) # (‘a’, ‘b’, ‘c’)
Python
colors = (“red”, “green”, “blue”, “yellow”, “purple”)
# Index: 0 1 2 3 4
# Negative: -5 -4 -3 -2 -1
print(colors[0]) # red
print(colors[2]) # blue
print(colors[-1]) # purple (last item)
print(colors[-2]) # yellow (second last)
Python
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
print(numbers[2:6]) # (2, 3, 4, 5)
print(numbers[:4]) # (0, 1, 2, 3)
print(numbers[6:]) # (6, 7, 8, 9)
print(numbers[::2]) # (0, 2, 4, 6, 8)
print(numbers[::-1]) # (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
Python
colors = (“red”, “green”, “blue”)
# This causes an error
# colors[0] = “yellow” # TypeError: ‘tuple’ object does not support item assignment
# This causes an error
# colors.append(“yellow”) # AttributeError: ‘tuple’ object has no attribute ‘append’
# You cannot remove items either
# del colors[0] # TypeError: ‘tuple’ object doesn’t support item deletion
🕯️ Magic Note
Immutability is a feature, not a limitation. Because tuples cannot change, Python can optimize them. Tuples use less memory than lists and are slightly faster. They are also safe to use as dictionary keys (lists cannot be keys because they are mutable).
Python
numbers = (1, 2, 2, 3, 2, 4, 2, 5)
# .count() counts occurrences of a value
print(numbers.count(2)) # 4 (2 appears four times)
print(numbers.count(9)) # 0
# .index() finds the first occurrence
print(numbers.index(3)) # 3 (first 3 is at index 3)
print(numbers.index(2)) # 1 (first 2 is at index 1)
# .index() with start and end parameters
print(numbers.index(2, 2)) # 2 (search from index 2)
# .index() raises ValueError if not found
# numbers.index(9) # ValueError: tuple.index(x): x not in tuple
Python
coordinates = (10, 20, 30)
print(len(coordinates)) # 3
print(10 in coordinates) # True
print(99 in coordinates) # False
print(10 not in coordinates) # False
print(99 not in coordinates) # True
# Empty tuple is falsy
empty = ()
if empty:
print(“This won’t print”)
else:
print(“Empty tuple is falsy”)
Python
colors = (“red”, “green”, “blue”)
# Basic loop
for color in colors:
print(color)
# red
# green
# blue
# Loop with index using enumerate
for i, color in enumerate(colors):
print(f”{i}: {color}”)
# 0: red
# 1: green
# 2: blue
Python
# Tuple packing (comma creates a tuple)
point = 10, 20
print(point) # (10, 20)
# Tuple unpacking
x, y = point
print(x) # 10
print(y) # 20
# Multiple assignment (uses tuple unpacking)
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
# Swapping variables (tuple unpacking magic)
x = 5
y = 10
x, y = y, x
print(x, y) # 10 5
# Unpacking with star (*) for remaining items
numbers = (1, 2, 3, 4, 5)
first, *rest = numbers
print(first) # 1
print(rest) # [2, 3, 4, 5] (rest becomes a list)
🕯️ Magic Note
Tuple unpacking is everywhere in Python. The multiple assignment a, b = 1, 2 is actually tuple packing and unpacking. The swap x, y = y, x uses tuple unpacking. This is elegant, readable, and very Pythonic.
Python
# Tuple as a dictionary key (valid)
coordinates = {
(0, 0): “origin”,
(1, 0): “right”,
(0, 1): “up”,
(1, 1): “diagonal”
}
print(coordinates[(1, 0)]) # right
# List as a dictionary key (invalid)
# invalid = {[1, 2]: “list”} # TypeError: unhashable type: ‘list’
# Tuple with mutable items is also invalid
# invalid = {([1, 2], 3): “nested_list”} # TypeError: unhashable type: ‘list’
Python
# Tuple to list (becomes mutable)
colors_tuple = (“red”, “green”, “blue”)
colors_list = list(colors_tuple)
colors_list.append(“yellow”)
print(colors_list) # [‘red’, ‘green’, ‘blue’, ‘yellow’]
# List to tuple (becomes immutable)
numbers_list = [1, 2, 3]
numbers_tuple = tuple(numbers_list)
print(numbers_tuple) # (1, 2, 3)
# numbers_tuple.append(4) # Error! Tuples cannot be changed
| Use a Tuple When... | Use a List When... |
|---|---|
| Data should never change | Data needs to change (add, remove, modify) |
| You need a dictionary key | You do not need dictionary keys |
| You are returning multiple values from a function | You need to collect items dynamically |
| The data has fixed meaning (RGB, coordinates, dates) | The data is a collection of similar items |
| You want better performance and less memory | You need flexibility over speed |
Python
# Good tuple examples (fixed, meaningful data)
rgb = (255, 128, 0)
coordinates = (40.7128, -74.0060)
days = (“Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”)
# Good list examples (dynamic collections)
scores = [95, 87, 92, 88, 96]
tasks = [“write code”, “test”, “deploy”]
shopping_cart = [“apple”, “bread”, “milk”]
- Forgetting the comma for single-item tuples: (5) is not a tuple, (5,) is
- Trying to modify a tuple: my_tuple[0] = 10 causes TypeError
- Using a tuple with mutable items as a dictionary key (unhashable)
- Confusing tuple unpacking with list indexing
- Calling .append() or .remove() on a tuple
- Expecting a tuple to be mutable when it is not
- How do you create a tuple with a single item containing the number 42?
- What happens if you try to change an item in a tuple?
- Write code that swaps the values of a and b using tuple unpacking.
- Why can a tuple be used as a dictionary key but a list cannot?
- How do you convert a list named my_list into a tuple?
- What is the output of len((1, 2, 3, 2, 1))?
⚡ Whisper
A tuple is a promise. You write the items once, in a specific order, and they stay exactly that way forever. No one can add to it. No one can remove from it. No one can rearrange it. This is not weakness. This is trust. When you pass a tuple to another part of your program, you know it will not be changed behind your back. When you use a tuple as a dictionary key, you know it will always find the same value. A tuple says: “Here is my truth. It does not change.” In a world of mutable lists, be a tuple. Be reliable. Be steady.