A tuple in Python is a collection data type that is:
my_tuple = (10, 20, 30, "hello", 3.14)
print(my_tuple) # (10, 20, 30, 'hello', 3.14)
Tuples are created using () or without parentheses:
# With parentheses
numbers = (1, 2, 3)
# Without parentheses (tuple packing)
student = "Alice", 21, "CS"
# Single element tuple must have a comma
x = (5,) # tuple
y = (5) # just an integer
student = ("Alice", 21, "CS")
print(student[0]) # Alice
print(student[-1]) # CS (negative index)
Tuples cannot be modified after creation:
numbers = (1, 2, 3)
numbers[0] = 10 # ❌ Error: 'tuple' object does not support item assignment
Tuples have only a few built-in methods:
| Method | Description | Example |
|---|---|---|
count() |
Returns number of occurrences of an element | |
index() |
Returns the index of first occurrence of an element | |
t1 = (1, 2)
t2 = (3, 4)
# Concatenation
print(t1 + t2) # (1, 2, 3, 4)
# Repetition
print(t1 * 3) # (1, 2, 1, 2, 1, 2)
# Membership
print(2 in t1) # True
# Returning multiple values
def get_student():
return ("Alice", 21, "CS")
name, age, course = get_student()
print(name, age, course) # Alice 21 CS
| Feature | List | Tuple |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutable? | ✅ Yes | ❌ No |
| Performance | Slower | Faster |
| Use case | When data changes | When data is constant |