🔒 What is a Tuple in Python?
A tuple is an ordered and immutable (unchangeable) collection of items enclosed in parentheses ().
Unlike lists, once a tuple is created, its elements cannot be modified, added, or removed. This makes tuples faster in performance and ideal for storing constant records, GPS coordinates, configuration settings, and database row projections.
1. Basic Tuple Declaration and Indexing
Create a tuple and access its elements using zero-based index positions.
Python
# Declaring a tuple of server configurations
server_config = ("192.168.1.10", 8080, "Production")
print("Server IP:", server_config[0])
print("Port Number:", server_config[1])
print("Environment:", server_config[2])
Output:
Server IP: 192.168.1.10
Port Number: 8080
Environment: Production
Real-Time Example 1: Geographic GPS Coordinate Storing
Store permanent latitude and longitude coordinates for map tracking applications.
Python
# Pune office latitude and longitude
office_location = (18.5204, 73.8567)
print(f"Latitude: {office_location[0]}")
print(f"Longitude: {office_location[1]}")
Output:
Latitude: 18.5204
Longitude: 73.8567
Real-Time Example 2: Tuple Unpacking
Extract values from a tuple directly into distinct variables in a single statement.
Python
user_record = ("Rahul Sharma", 28, "Software Engineer")
# Tuple unpacking
name, age, profession = user_record
print("Name:", name)
print("Age:", age)
print("Profession:", profession)
Output:
Name: Rahul Sharma
Age: 28
Profession: Software Engineer
Real-Time Example 3: Returning Multiple Values from Functions
Python functions can return multiple calculated results packed automatically as a tuple.
Python
def calculate_cart_summary(prices):
total = sum(prices)
highest = max(prices)
lowest = min(prices)
return total, highest, lowest # Packed as tuple
cart_totals = [450, 1200, 300, 850]
tot, high, low = calculate_cart_summary(cart_totals)
print(f"Total: ₹{tot} | Highest: ₹{high} | Lowest: ₹{low}")
Output:
Total: ₹2800 | Highest: ₹1200 | Lowest: ₹300
Real-Time Example 4: Immutable Data Protection (Constant Records)
Demonstrate how tuples protect fixed data from accidental modification during program execution.
Python
days_of_week = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
try:
# Attempting to modify an element will raise an error
days_of_week[0] = "Holiday"
except TypeError as e:
print("TypeError caught successfully:", e)
Output:
TypeError caught successfully: 'tuple' object does not support item assignment
Real-Time Example 5: RGB Color Code Configuration
Store UI theme color codes using immutable tuples for design systems.
Python
PRIMARY_BLUE = (55, 118, 171)
WARNING_YELLOW = (255, 212, 59)
print(f"RGB Red channel for primary theme: {PRIMARY_BLUE[0]}")
print(f"RGB Green channel for warning theme: {WARNING_YELLOW[1]}")
Output:
RGB Red channel for primary theme: 55
RGB Green channel for warning theme: 212
Real-Time Example 6: Database Record Rows (SQL Projections)
Represent fetched database rows as tuples to maintain fixed schema integrity.
Python
# Simulated SQL query result rows: (ID, ItemName, Price)
database_rows = [
(101, "Wireless Mouse", 450),
(102, "Mechanical Keyboard", 1200),
(103, "USB-C Hub", 850)
]
for row in database_rows:
item_id, name, price = row
print(f"ID: {item_id} | Product: {name} | Price: ₹{price}")
Output:
ID: 101 | Product: Wireless Mouse | Price: ₹450
ID: 102 | Product: Mechanical Keyboard | Price: ₹1200
ID: 103 | Product: USB-C Hub | Price: ₹850
Real-Time Example 7: Tuple Methods (count() and index())
Query tuple elements using built-in
count() and index() methods.
Python
status_logs = ("INFO", "DEBUG", "INFO", "WARNING", "INFO", "ERROR")
info_count = status_logs.count("INFO")
first_error_index = status_logs.index("ERROR")
print(f"Total 'INFO' logs found: {info_count}")
print(f"First 'ERROR' found at index position: {first_error_index}")
Output:
Total 'INFO' logs found: 3
First 'ERROR' found at index position: 5
Real-Time Example 8: Using Tuples as Dictionary Keys
Because tuples are immutable, they can be used as dictionary keys (unlike lists).
Python
# Mapping coordinate pairs (tuples) to location names
location_directory = {
(18.5204, 73.8567): "Pune Headquarters",
(19.0760, 72.8777): "Mumbai Branch Office"
}
query_coord = (18.5204, 73.8567)
print(f"Location lookup for {query_coord}: {location_directory[query_coord]}")
Output:
Location lookup for (18.5204, 73.8567): Pune Headquarters
Real-Time Example 9: Swapping Variable Values Using Tuples
Perform elegant variable value swapping in Python utilizing tuple assignment packing.
Python
x = 10
Y = 20
print(f"Before Swap: x = {x}, y = {Y}")
# Tuple-based swap
x, Y = Y, x
print(f"After Swap: x = {x}, y = {Y}")
Output:
Before Swap: x = 10, y = 20
After Swap: x = 20, y = 10