Python Tuples & Unpacking
A tuple (tuple) is an ordered, immutable collection enclosed in parentheses ((...)).
The Single-Element Comma Rule: In Python, parentheses are also used for mathematical grouping. Therefore, writing (50) creates an integer 50, NOT a tuple! To create a single-element tuple, a trailing comma is strictly mandatory: (50,).
# 1. Creating multi-element tuples
point = (10, 20)
rgb_color = (255, 128, 0)
# 2. The Single-Element Comma Trap:
not_a_tuple = (50) # int!
is_a_tuple = (50,) # tuple!
print("point:", point, "| Type:", type(point).__name__)
print("not_a_tuple:", not_a_tuple, "| Type:", type(not_a_tuple).__name__)
print("is_a_tuple: ", is_a_tuple, "| Type:", type(is_a_tuple).__name__)
It is the comma that defines a tuple in Python, not just the parentheses.
Tuples are immutable. Once constructed in memory, elements cannot be replaced, added, or deleted. Attempting t[0] = 99 raises a fatal TypeError:
coordinates = (17.3850, 78.4867) # Hyderabad GPS coordinates
print("Latitude:", coordinates[0])
print("Longitude:", coordinates[1])
# Attempting to modify coordinates will raise TypeError:
try:
coordinates[0] = 18.0000
except TypeError as err:
print("\nโ Modification Prevented:", err)
- Data Protection: Guarantees that configuration constants (like database credentials, screen dimensions, or GPS coordinates) are write-protected.
- Hashability: Tuples can serve as keys in dictionaries and elements in sets (lists cannot!).
Tuple Unpacking extracts items from a tuple directly into variables in a single step. Extended star unpacking (*rest) captures any remaining items into a list:
# 1. Standard Tuple Unpacking:
user_data = ("Balaji", "Hyderabad", "India")
name, city, country = user_data
print(f"Name: {name}, City: {city}, Country: {country}")
# 2. Extended Star Unpacking (*rest):
scores = (98, 92, 85, 78, 64)
first, second, *remaining = scores
print(f"\nFirst Place: {first}")
print(f"Second Place: {second}")
print(f"Remaining Scores (List): {remaining}")
You can place *rest anywhere: first, *middle, last = my_tuple cleanly isolates the head and tail while grouping everything in between.
Because tuples cannot be mutated, they have exactly two built-in methods:
t.count(x): Returns the number of occurrences ofx.t.index(x): Returns the index of the first occurrence ofx.
grades = ("A", "B", "A", "C", "A", "B")
# Count how many students scored 'A'
count_a = grades.count("A")
print("Total 'A' grades:", count_a)
# Find first position of 'C'
first_c_pos = grades.index("C")
print("First 'C' grade at index:", first_c_pos)
Both methods run efficiently across immutable sequences without altering underlying memory.
Writing x = (10) creates an integer 10. To create a 1-element tuple, write x = (10,). Without the comma, Python treats parentheses as mathematical grouping.
Create a tuple of 5 student marks. Unpack the highest mark, lowest mark, and group the middle marks using star unpacking.
scores = (95, 88, 82, 79, 65)
highest, *middle, lowest = scores
print("Highest Score:", highest)
print("Middle Scores:", middle)
print("Lowest Score:", lowest)
Q Why are tuples more memory-efficient than lists?
Lists allocate extra buffer space to accommodate future append() operations. Tuples are fixed-size and allocate the exact required memory bytes with zero overhead.
Q Can a tuple contain a mutable object like a list?
Yes! A tuple can hold a list: t = (1, [2, 3]). While you cannot reassign t[1] to a new object, you can mutate the list in place (t[1].append(4) is valid!).
Q When should I use a Tuple instead of a List?
Use tuples for heterogeneous records with fixed schema (e.g. database rows, (x, y) coordinates, RGB colors) where values must not change. Use lists for homogeneous collections of dynamic size.