()
.Feature | Description |
---|---|
Ordered | Elements have a fixed position/index |
Immutable | Cannot be changed (no add/remove/update) |
Allows Duplicates | Yes |
Heterogeneous | Can contain different data types (int, str, etc) |
my_tuple = (10, "apple", 3.14)
empty_tuple = ()
single_element_tuple = (5,) # Notice the comma
mixed_tuple = (1, "Hello", 3.14)
✅ Note: A single-element tuple must have a comma, otherwise it's not a tuple.
t = (10, 20, 30, 40)
print(t[0]) # Output: 10
print(t[-1]) # Output: 40 (last element)
print(t[1:3]) # Output: (20, 30)
# Packing
person = ("Abhi", 30, "Data Scientist")
# Unpacking
name, age, profession = person
print(name) # Output: Abhi
print(profession) # Output: Data Scientist
nested = (1, [2, 3], (4, 5))
print(nested[1][0]) # Output: 2
Even though tuples are immutable, if they contain a mutable object (like a list), that object can be modified.
Method | Description |
---|---|
.count(x) |
Returns the number of times x appears |
.index(x) |
Returns the index of the first x |
t = (1, 2, 3, 2, 2, 4)
print(t.count(2)) # Output: 3
print(t.index(3)) # Output: 2
for item in t:
print(item)
t = (1, 2, 3)
# t[0] = 10 ❌ Error: 'tuple' object does not support item assignment
# t.append(4) ❌ Error: 'tuple' object has no attribute 'append'
Data that should not change (e.g., coordinates, days of the week)
As dictionary keys
For faster access (tuples are slightly faster than lists)
+-----------------------------+
| TUPLE |
+-----------------------------+
| Ordered ✅ |
| Immutable ✅ |
| Duplicates ✅ |
| Indexed ✅ |
+-----------------------------+
| Example: (1, "a", 3.14) |
+-----------------------------+