Python Tuple Type
What Is a Tuple?
A tuple is an immutable sequence type in Python, used to store collections of items. Once a tuple is created, its contents cannot be changed (no adding, removing, or modifying items).
Creating Tuples
You can create a tuple using parentheses, commas, or the tuple()
constructor:
empty = ()
singleton = (42,) # Note the comma for a single-item tuple
data = (1, "hello", 3.14)
no_parens = 1, 2, 3 # Parentheses are optional
from_iterable = tuple([1, 2, 3])
Accessing Tuples
You can access items by index and slice tuples:
t = ("a", "b", "c")
print(t[0]) # 'a'
print(t[-1]) # 'c'
print(t[1:]) # ('b', 'c')
Common Tuple Operations
Tuples support many of the same operations as lists:
t = (1, 2, 3)
print(len(t)) # 3
print(t + (4, 5)) # (1, 2, 3, 4, 5) (concatenation)
print(t * 2) # (1, 2, 3, 1, 2, 3) (repetition)
print(2 in t) # True (membership)
Tuple Methods
Tuples have two built-in methods:
t = (1, 2, 2, 3)
print(t.count(2)) # 2 (number of times 2 appears)
print(t.index(3)) # 3 (index of first occurrence of 3)
Iterating Over Tuples
You can loop through tuples using a for
loop:
colors = ("red", "green", "blue")
for color in colors:
print(color)
Tuple Packing and Unpacking
You can assign multiple values at once using tuple packing and unpacking:
a, b, c = (1, 2, 3)
print(a, b, c) # 1 2 3
Nested Tuples
Tuples can contain other tuples (or lists):
nested = ((1, 2), (3, 4))
print(nested[1][0]) # 3
When to Use Tuples
- When you need an immutable sequence.
- For fixed collections of items (like coordinates, RGB colors, etc.).
- As dictionary keys or set elements (if all items are hashable).
Summary
- Tuples are immutable sequences for storing collections of items.
- Support indexing, slicing, and a few built-in methods.
- Use parentheses or commas to create tuples.
- Tuples can contain any type, including other tuples or lists.