beginner
Tuples in Python
5 min read
Overview
A Tuple is an ordered collection of values enclosed in parentheses (). Unlike lists, tuples are immutable, meaning once a tuple is created, its elements cannot be changed, added, or removed.
Learning Objectives
- Create tuples and access items using 0-based indexing.
- Use tuple packing and unpacking.
- Understand why tuples are faster and consume less memory than lists.
Concept Explanation
In simple words, think of a tuple as a locked read-only list:
- Ordered: Elements maintain a fixed sequence.
- Immutable: You cannot modify items after creation.
- Hashable: Because tuples cannot change, tuples containing immutable items can be used as dictionary keys or set elements.
Code Examples
Example 1 — Creating & Accessing Tuples
python
# Creating a tuple
point = (10, 20, 30)
# Accessing elements
print("X Coordinate:", point[0])
print("Y Coordinate:", point[1])
# Single element tuple requires a comma
single_item = ("data",)
print(type(single_item)) # <class 'tuple'>
Example 2 — Tuple Unpacking
Extracting tuple values directly into variables:
python
# Unpacking coordinates
x, y, z = point
print(f"X={x}, Y={y}, Z={z}")
# Swap variables without a temporary variable using tuples
a = 5
b = 10
a, b = b, a
print(f"a={a}, b={b}") # a=10, b=5
Common Mistakes
- Forgetting the comma for single-item tuples: Writing
x = (5)creates an integer5, not a tuple. You must writex = (5,). - Attempting item assignment: Writing
point[0] = 50raises aTypeError.
Best Practices
- Use tuples for fixed data structures (e.g. database records, coordinates, function return values).
- Use tuples as keys in dictionaries when multi-part keys are required.