4.2 Tuples
Understanding tuples as immutable sequences, when to prefer them over lists, and how to use them for data safety and integrity.
Tuples are similar to lists, but they have a crucial feature: they are immutable. This means that once a tuple is created, you cannot change, add, or remove items from it. This property gives them speed and safety.
Key features of tuples:
- Ordered: Items maintain their order.
- Immutable: Cannot be modified after creation.
- Allow Duplicate Items: Just like lists.
- Can Contain Different Data Types: Just like lists.
Tuples are declared using parentheses `()`, with items separated by commas.
Creating a Tuple
Important Note: To create a tuple with a single item, you must add a comma after the item, otherwise Python will interpret it as a simple value in parentheses.
# Creating tuples
# Tuple of numbers
coordinates = (10, 20, 30)
print(f"Tuple of coordinates: {coordinates}, Type: {type(coordinates)}")
# Tuple of strings
rgb_colors = ("red", "green", "blue")
print(f"Tuple of colors: {rgb_colors}")
# Tuple of mixed types
product_info = ("Laptop", 1200.50, True)
print(f"Tuple of product info: {product_info}")
# Tuple with duplicates
duplicate_tuple = (1, 2, 2, 3, 1)
print(f"Tuple with duplicates: {duplicate_tuple}")
# Empty tuple
empty_tuple = ()
print(f"Empty tuple: {empty_tuple}")
# Tuple with a single element (the comma is important!)
single_element_tuple = ("single",)
print(f"Single-element tuple: {single_element_tuple}, Type: {type(single_element_tuple)}")
# Without a comma, it's not a tuple!
not_a_tuple = ("single")
print(f"Without a comma (not a tuple): {not_a_tuple}, Type: {type(not_a_tuple)}")
Accessing Items and Unpacking
Accessing tuple items is done the same way as with lists: through indexing and slicing. A powerful feature is "unpacking," where you can assign the items of a tuple to multiple variables at once.
# Accessing tuple items and unpacking
date_tuple = (2025, 7, 18) # (Year, Month, Day)
# Unpacking
year, month, day = date_tuple
print(f"Year: {year}, Month: {month}, Day: {day}")
# Slicing tuples
date_part = date_tuple[1:3]
print(f"Date part: {date_part}")
Immutability of Tuples
Due to their immutability, you cannot use methods like `append()`, `insert()`, `remove()`, `pop()`, `sort()`, or assign a value to an index.
# Attempting to modify a tuple (will cause an error!)
my_tuple_to_change = (1, 2, 3)
try:
# my_tuple_to_change[0] = 10 # This line will cause a TypeError
print("The tuple is immutable. You cannot change its items.")
except TypeError as e:
print(f"A TypeError occurred: {e}")
try:
# my_tuple_to_change.append(4) # This will cause an AttributeError
print("The tuple does not have an append() method.")
except AttributeError as e:
print(f"An AttributeError occurred: {e}")
Tip!
When to use a Tuple?
- Data Integrity: When you want to be sure that the data will not be accidentally changed (e.g., constant RGB coordinates, settings).
- Performance: Tuples are generally slightly faster and consume less memory than lists.
- Dictionary Keys: Because they are immutable, tuples can be used as keys in dictionaries, whereas lists cannot.
- Returning Multiple Values: Functions that return multiple values actually return a tuple.
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.