Tuples (Immutability & Unpacking)
When you have data that should never be altered after creation—like GPS coordinates or database IDs—tuples provide safe, immutable storage.
What is it?
A Python `tuple` is an ordered, immutable collection of elements enclosed in parentheses `(item1, item2)`.
Why is it used?
Guarantees data integrity, is faster than lists, and can be used as dictionary keys (because tuples are hashable).
Detailed Explanation
Tuple Properties:
• Immutability: Once created, elements cannot be added, removed, or changed. Calling `t[0] = 5` raises `TypeError`.
• Single Element Tuple: Must have a trailing comma: `single = (42,)`. Without the comma, Python treats `(42)` as plain integer in parentheses.
• Tuple Unpacking: Assigning tuple elements directly into individual variables in one clean statement: `x, y = coordinates`.
Syntax Structure
Syntax Blueprint
point = (19.1557, 77.3168) # Nanded Coordinates
lat, lng = point # Unpacking
Code Example
PYTHON Code
# Geographic Coordinates for IGM Campus Nanded
campus_coords = (19.1557, 77.3168)
# Tuple Unpacking
latitude, longitude = campus_coords
print(f"Latitude: {latitude}° N")
print(f"Longitude: {longitude}° E")
# Multiple return values from functions (uses tuples!)
def get_min_max(numbers):
return min(numbers), max(numbers) # Returns tuple
low, high = get_min_max([45, 12, 89, 74, 99])
print(f"Low: {low}, High: {high}")
# Swapping variables without a temporary variable
a = 10
b = 20
a, b = b, a # Pythonic tuple swap!
print(f"Swapped: a={a}, b={b}")
Explanation of the Code
• `latitude, longitude = campus_coords` unpacks both coordinates.
• Functions returning multiple values actually return a tuple.
• `a, b = b, a` performs an instantaneous tuple swap.
Expected Output
Latitude: 19.1557° N
Longitude: 77.3168° E
Low: 12, High: 99
Swapped: a=20, b=10
Real-World Application
Used for database connection tuples `(host, port)`, RGB color codes, and SQL query parameter bindings.
Common Mistakes to Avoid
• Forgetting the trailing comma for single item tuples: `x = (5)` is an int; `x = (5,)` is a tuple.
• Trying to mutate tuple items (raises `TypeError`).
Quick Practice Challenge
Swap two variables `x = 'Red'` and `y = 'Blue'` using Pythonic tuple unpacking.
Key Takeaways
• Tuples are immutable and defined with parentheses `()`.
• Unpacking allows multiple variable assignments in one statement.
• Functions returning multiple values return a tuple under the hood.