Tuples are ordered collections, like lists, but they are immutable. Once created, their elements cannot be changed.
1) What is a Tuple?
A tuple is an ordered, immutable collection of items, enclosed in parentheses ( ).
Tuples can contain mixed data types, including other tuples.
# Examples
empty_tuple = ()
single_item = (5,) # Note the comma for single-item tuple
numbers = (1, 2, 3, 4)
mixed = ("Alice", 25, True)
nested = (1, (2, 3), [4, 5])
2) Accessing Elements
Tuples support indexing and slicing just like lists:
numbers = (10, 20, 30, 40)
print(numbers[0]) # 10
print(numbers[-1]) # 40
print(numbers[1:3]) # (20, 30)
Note: Tuples are immutable, so you cannot modify elements directly.
3) Tuple Operations
You can perform common operations such as concatenation, repetition, and checking membership:
a = (1, 2)
b = (3, 4)
# Concatenation
c = a + b
print(c) # (1, 2, 3, 4)
# Repetition
d = a * 3
print(d) # (1, 2, 1, 2, 1, 2)
# Membership
print(2 in a) # True
print(5 not in b) # True
4) Common Tuple Methods
count(x)– Returns the number of times x appearsindex(x)– Returns the first index of x
Since tuples are immutable, methods that modify the data (like append, remove) are not available.
5) Advantages of Tuples
- Immutability ensures data cannot be changed accidentally
- Tuples can be used as keys in dictionaries
- Faster than lists for read-only operations
- Safer for storing constant values
6) Common Mistakes
- Forgetting the comma in a single-element tuple →
single = (5) ❌(this is just an int) - Trying to modify a tuple →
t[0] = 10 ❌raisesTypeError - Using mutable objects inside tuples without caution (e.g., lists inside tuple can be modified)
No comments:
Post a Comment