Lesson 13 of 19 · 2 min
Tuples — Ordered but Immutable
WHY Tuples?
A tuple is a sealed collection — once created, nothing inside can be changed. Use tuples when data must never be accidentally modified: GPS coordinates, RGB colour values, database primary keys. Tuples are slightly faster than lists and can be used as dictionary keys (lists cannot).
Creating Tuples
coords = (28.6, 77.2) # GPS: latitude, longitude — fixed forever
rgb_red = (255, 0, 0) # Red colour — these values are constants
months = ("Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec") # all 12 months
single = (42,) # SINGLE-item tuple MUST have a trailing comma!
# Without it: (42) is just the integer 42 in parentheses
empty = () # empty tuple
point = 10, 20 # parentheses are optional — the comma creates the tuple
print(type(point)) # <class 'tuple'>
Output: <class 'tuple'>
Accessing Tuple Elements
coords = (28.6, 77.2, 216.0) # latitude, longitude, altitude print(coords[0]) # 28.6 — same indexing as lists (zero-based) print(coords[-1]) # 216.0 — negative indexing works too print(coords[0:2]) # (28.6, 77.2) — slicing returns a new tuple print(len(coords)) # 3 — total number of elements
Output: 28.6 216.0 (28.6, 77.2) 3
Tuples are Immutable — Cannot Be Changed
colors = ("red", "green", "blue")
# These both CRASH — tuples cannot be modified:
# colors[0] = "yellow" # TypeError: 'tuple' object does not support item assignment
# colors.append("purple") # AttributeError: 'tuple' object has no attribute 'append'
# To "add" to a tuple, create a NEW one using concatenation
new_colors = colors + ("yellow",) # concatenate → creates a brand new tuple
print(new_colors) # ('red', 'green', 'blue', 'yellow')
print(colors) # ('red', 'green', 'blue') — original is UNCHANGED
Output:
('red', 'green', 'blue', 'yellow')
('red', 'green', 'blue')Tuple Unpacking — Elegant Multi-Variable Assignment
# Assign tuple elements to variables in ONE line
lat, lon = (28.6, 77.2) # lat=28.6, lon=77.2
print(f"Lat: {lat}, Lon: {lon}")
name, age, city = ("Priya", 20, "Chennai") # 3-element unpack
print(name, age, city)
# Functions that return multiple values use tuples under the hood
def get_bounds():
return 0, 100 # Python packs 0 and 100 into tuple (0, 100)
low, high = get_bounds() # unpack the returned tuple
print(f"Low: {low}, High: {high}")
Output: Lat: 28.6, Lon: 77.2 Priya 20 Chennai Low: 0, High: 100
