Tuples
A tuple is an ordered, immutable collection of items. Once created, you cannot change its elements. Tuples are often used for fixed data like coordinates or database records.
Creating Tuples
Use parentheses, or just separate values with commas.
point = (3, 5)
colors = "red", "green", "blue"
single = (42,) # note the trailing comma
empty = ()
Accessing Elements
Same indexing and slicing as lists, but you cannot modify them.
print(point[0]) # 3
print(colors[-1]) # blue
# point[0] = 10 # TypeError: tuple does not support item assignment
Tuple Packing and Unpacking
Assign multiple values at once.
a, b = 1, 2 # packing and unpacking
x, y = point # x=3, y=5
When to Use Tuples
- Data that should not change (like days of week, constant settings).
- Return multiple values from a function.
- As dictionary keys (since they are hashable).
Two Minute Drill
- Tuples are immutable, ordered collections.
- Created with parentheses or commas; a single-element tuple needs a comma.
- Index and slice like lists, but cannot be changed.
- Unpacking assigns tuple elements to variables.
- Faster and safer for fixed data.
Need more clarification?
Drop us an email at career@quipoinfotech.com
