Creating Tuples
Tuples use parentheses (optional but recommended). A single-element tuple requires a trailing comma.
Python
# Creating tuples
t1 = (1, 2, 3)
t2 = "a", "b", "c" # Parentheses optional
t3 = (42,) # Single element - MUST have comma!
t4 = () # Empty tuple
print(t1) # (1, 2, 3)
print(t2) # ('a', 'b', 'c')
print(t3) # (42,)
print(type(t4)) #
βΆ Output
(1, 2, 3)
('a', 'b', 'c')
(42,)
Accessing Tuple Elements
Same indexing and slicing as lists.
Python
coords = (10, 20, 30)
print(coords[0]) # 10 - first element
print(coords[-1]) # 30 - last element
print(coords[1:]) # (20, 30) - slice
# But you CANNOT modify:
try:
coords[0] = 99
except TypeError as e:
print(f"Error: {e}")
βΆ Output
10
30
(20, 30)
Error: 'tuple' object does not support item assignment
Ad β 336Γ280
Tuple Unpacking
Assign tuple elements to individual variables β a very Pythonic pattern.
Python
# Basic unpacking
point = (4, 7)
x, y = point
print(f"x={x}, y={y}")
# Swap variables (uses tuple packing/unpacking)
a, b = 10, 20
a, b = b, a
print(f"a={a}, b={b}") # a=20, b=10
# Extended unpacking with *
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]
βΆ Output
x=4, y=7
a=20, b=10
1
[2, 3, 4, 5]
When to Use Tuples vs Lists
Use a tuple when data should not change. Use a list when you need to modify the collection.
Python
# β
Tuples for fixed data
RGB_RED = (255, 0, 0)
DAYS_OF_WEEK = ("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
DATABASE_CONFIG = ("localhost", 5432, "mydb")
# β
Lists for mutable collections
cart_items = ["apple", "banana"]
cart_items.append("orange") # Can modify
# β
Tuples as dict keys (lists cannot be dict keys)
location_data = {(40.7128, -74.0060): "New York"}