Tuples are ordered collections similar to lists, but they cannot be changed after creation. This makes them useful for data that should stay fixed.
What is a tuple?
A tuple is created with parentheses () and items separated by commas.
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_item = (5,) # Note the comma for one item
You can also create a tuple without parentheses:
point = 3, 4
An empty tuple:
empty_tuple = ()
Tuples can contain mixed types and are immutable.
Accessing elements
Use indexes just like lists (starting at 0).
colors = ("red", "green", "blue")
print(colors[0]) # red
print(colors[-1]) # blue
Slicing works too:
print(colors[1:3]) # ("green", "blue")
Why use tuples instead of lists?
- Tuples are immutable: you cannot add, remove, or change items.
- This protects data from accidental changes.
- Tuples are faster than lists.
- Tuples can be used as dictionary keys (lists cannot).
Attempting to modify raises an error:
colors[0] = "yellow" # TypeError: 'tuple' object does not support item assignment
Common operations
Get length:
print(len(colors)) # 3
Check membership:
print("green" in colors) # True
Loop over a tuple:
for color in colors:
print(color)
Packing and unpacking
Tuples make it easy to assign multiple values.
Packing:
person = ("Alex", 25, "Berlin")
Unpacking:
name, age, city = person
print(name) # Alex
print(age) # 25
This works with functions too:
def get_point():
return (10, 20)
x, y = get_point()
print(x, y) # 10 20
Simple examples
Store fixed settings:
screen_size = (1920, 1080) # Cannot be changed accidentally
RGB color values:
red = (255, 0, 0)
Quick summary
- Create tuples with parentheses (and a comma for single items).
- Access elements with indexes and slicing.
- Tuples are immutable and faster than lists.
- Use unpacking to assign multiple values easily.
- Choose tuples for data that should not change.
Practice using tuples for fixed collections. They are a safe and efficient alternative to lists in Python programs.
Top comments (0)