A tuple in Python is a collection of items stored in a single variable, similar to a list. However, the key difference is:
Tuples are immutable (cannot be changed after creation)
tuple_name = (elements)numbers = (1, 2, 3)names = ("Amit", "Rahul", "Priya")mixed = (10, "Python", 3.5)t = (5,)👉 Comma is required, otherwise it is not considered a tuple.
numbers = (10, 20, 30) print(numbers[0])print(numbers[1])Output
1020print(numbers[-1])Output
30numbers = (1, 2, 3, 4, 5) print(numbers[1:4])Output
(2, 3, 4)numbers = (1, 2, 3) numbers[1] = 10 # ErrorExplanation
a = (1, 2)b = (3, 4) print(a + b)print((1, 2) * 2)print(2 in (1, 2, 3))numbers = (1, 2, 3) for n in numbers: print(n)t = 1, 2, 3a, b, c = (1, 2, 3) print(a, b, c)t = ((1, 2), (3, 4)) print(t[0][1])Output
2| Function | Description |
|---|---|
len() | Returns number of elements |
max() | Returns maximum value |
min() | Returns minimum value |
sum() | Returns sum of elements |
| Feature | List | Tuple |
|---|---|---|
| Mutability | Mutable | Immutable |
| Syntax | [ ] | ( ) |
| Performance | Slower | Faster |
| Usage | Changeable data | Fixed data |
A tuple is an ordered and immutable collection
Created using parentheses ( )
Supports:
Cannot be modified after creation
Useful for fixed and secure data