Python Tuples
A tuple is an ordered, immutable collection that stores several values inside a single object.
What is a tuple?
A tuple groups related values together in a fixed sequence. It behaves much like a list, but with one defining difference: once a tuple is created, you cannot add, remove, or replace its elements. This quality is called immutability, and it makes tuples a natural fit for data that should stay constant while your program runs, such as coordinates, RGB colours, or a database record.
You build a tuple by placing comma-separated values inside round brackets. Tuples keep their order, so the first value you write is always at position zero, and they allow duplicate values.
Creating a tuple
colors = ("red", "green", "blue")
print(colors)
print(type(colors))
# Duplicates and mixed types are allowed
mixed = ("cat", 42, True, "cat")
print(mixed)Tuple characteristics
- Ordered: items keep the position in which they were defined.
- Immutable: the contents cannot be changed after creation.
- Indexed: each item has a position starting at 0.
- Allows duplicates: the same value can appear more than once.
- Can hold mixed data types in the same tuple.
Length and the tuple() constructor
Use the built-in len() function to count how many items a tuple contains. You can also build a tuple from another iterable using the tuple() constructor, which is handy when converting a list or a range into an immutable form.
Length and construction
fruits = ("apple", "banana", "cherry")
print(len(fruits)) # 3
# Build a tuple from a list
numbers = tuple([1, 2, 3, 4])
print(numbers) # (1, 2, 3, 4)Exercise: Python Tuples
What is the main characteristic that distinguishes a tuple from a list?