After learning about lists, which are flexible containers for ordered data that you can change, we now turn our attention to another built-in sequence type: the tuple. At first glance, tuples look very similar to lists, but they have one significant difference: they are immutable. This means that once a tuple is created, its contents cannot be altered, added to, or removed.
Think of a tuple as a fixed sequence of items. If you have a collection of values that represents something constant, like the coordinates of a point (x, y) or the RGB values for a specific color, a tuple is often a more appropriate choice than a list.
You create tuples using parentheses ()
instead of the square brackets []
used for lists. The items within the tuple are separated by commas.
# An empty tuple
empty_tuple = ()
print(empty_tuple)
# A tuple with integers
coordinates = (10, 20)
print(coordinates)
# A tuple with mixed data types
person_info = ("Alice", 30, "New York")
print(person_info)
# Parentheses are sometimes optional if the context is clear
another_tuple = 100, 200, 300
print(another_tuple)
print(type(another_tuple)) # Output: <class 'tuple'>
Creating a Single-Item Tuple
Creating a tuple with only one item requires a special syntax: you must include a trailing comma after the item. Without the comma, Python interprets the parentheses as standard grouping parentheses, not as defining a tuple.
# This is NOT a tuple, it's just the integer 5
not_a_tuple = (5)
print(type(not_a_tuple)) # Output: <class 'int'>
# This IS a single-item tuple
single_item_tuple = (5,)
print(type(single_item_tuple)) # Output: <class 'tuple'>
print(single_item_tuple)
This trailing comma tells Python explicitly that you intend to create a tuple, even with just one element.
Accessing elements within a tuple works exactly the same way as with lists. You use square brackets []
with the index of the element you want to retrieve. Remember that indexing starts at 0.
rgb_color = (255, 165, 0) # Orange color
# Access the first element (index 0)
red_value = rgb_color[0]
print(f"Red: {red_value}") # Output: Red: 255
# Access the third element (index 2)
blue_value = rgb_color[2]
print(f"Blue: {blue_value}") # Output: Blue: 0
Slicing also works identically to lists, allowing you to get sub-sequences of the tuple.
weekdays = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
# Get elements from index 1 up to (but not including) index 4
mid_week = weekdays[1:4]
print(mid_week) # Output: ('Tue', 'Wed', 'Thu')
# Get the last two elements
weekend = weekdays[-2:]
print(weekend) # Output: ('Sat', 'Sun')
Here's where tuples fundamentally differ from lists. Once you create a tuple, you cannot change its elements. Attempting to assign a new value to an index in a tuple will result in a TypeError
.
my_tuple = (10, 20, 30)
print(my_tuple)
# Let's try to change the element at index 1
# This will cause an error!
# my_tuple[1] = 25 # Uncommenting this line leads to TypeError
# Similarly, you cannot add or remove elements
# Methods like append(), extend(), remove(), pop() do not exist for tuples
This immutability might seem like a limitation, but it's actually a feature that offers several advantages:
# Using a tuple as a dictionary key
location_temps = {
(40.7128, -74.0060): 22, # New York City coordinates -> temperature
(34.0522, -118.2437): 28, # Los Angeles coordinates -> temperature
}
print(location_temps[(40.7128, -74.0060)]) # Output: 22
# Trying to use a list as a key would cause a TypeError
# location_temps[[34.0522, -118.2437]] = 28 # Error!
Because they are immutable, tuples have very few built-in methods compared to lists. The two main methods are:
count(value)
: Returns the number of times value
appears in the tuple.index(value)
: Returns the index of the first occurrence of value
. Raises a ValueError
if the value is not found.numbers = (1, 2, 5, 2, 8, 2, 10)
# Count occurrences of the number 2
count_of_2 = numbers.count(2)
print(f"The number 2 appears {count_of_2} times.") # Output: The number 2 appears 3 times.
# Find the index of the first occurrence of 8
index_of_8 = numbers.index(8)
print(f"The number 8 first appears at index {index_of_8}.") # Output: The number 8 first appears at index 4.
# Trying to find a value not in the tuple raises an error
# index_of_99 = numbers.index(99) # Uncommenting this line leads to ValueError
Python allows for a convenient syntax related to tuples called packing and unpacking.
Packing: When you list values separated by commas without enclosing parentheses (often), Python automatically "packs" them into a tuple.
packed_data = "Max", 25, "Berlin" # Values are packed into a tuple
print(packed_data) # Output: ('Max', 25, 'Berlin')
print(type(packed_data)) # Output: <class 'tuple'>
Unpacking: You can assign the elements of a tuple to individual variables in a single assignment statement. The number of variables on the left must match the number of elements in the tuple.
point = (15, 40)
# Unpack the tuple into variables x and y
x, y = point
print(f"x coordinate: {x}") # Output: x coordinate: 15
print(f"y coordinate: {y}") # Output: y coordinate: 40
# This is useful for swapping variables too!
a = 10
b = 20
a, b = b, a # Pack (b, a) into a tuple, then unpack into a, b
print(f"a: {a}, b: {b}") # Output: a: 20, b: 10
Unpacking is frequently used when iterating over sequences of tuples or when functions return multiple values (which are often returned as a tuple).
So, when should you use a list, and when should you use a tuple?
Understanding the immutable nature of tuples is important. While they share sequence behaviors like indexing and slicing with lists, their inability to be changed makes them suitable for different programming situations where constancy is desired or required.
© 2025 ApX Machine Learning