Creating and accessing tuples
T = (4, 7, 2), E = (), S = (5,) (comma needed), P = 1, 2, 3 (brackets optional), tuple('ab') → ('a', 'b').
Read by index: T[0] = 4, T[-1] = 2. Tuples are immutable: T[0] = 5 gives TypeError. (If a tuple holds a list, that list itself can still change.)
Tuple operations
- Concatenation: (1, 2) + (3,) → (1, 2, 3)
- Repetition: (0, 1) * 2 → (0, 1, 0, 1)
- Membership: 7 in T → True
- Slicing: T[1:3] → (7, 2); T[::-1] → (2, 7, 4)
- Traversal:
for x in T: print(x)
Each operation makes a new tuple; the old one is unchanged.
Tuple functions and methods
| Function / method | T = (4, 7, 2, 7) |
|---|---|
| len(T) | 4 |
| T.count(7) | 2 |
| T.index(2) | 2 |
| min(T), max(T), sum(T) | 2, 7, 20 |
| sorted(T) | [2, 4, 7, 7] (a list) |
| tuple(list) | converts a list to a tuple |
There is no append, remove or sort method, because tuples cannot change.
Tuple assignment
Packing: t = 3, 8 puts values into one tuple. Unpacking: a, b = t gives a = 3, b = 8. The number of names must equal the number of values, or you get ValueError.
Swapping without a third variable: a, b = b, a. The right side is packed first, then unpacked into a and b.
A function can return several values as a tuple: q, r = divmod(17, 5) → 3, 2.
Nested tuples
S = ((1, 'Riya', 91), (2, 'Aman', 85))
print(S[1][1]) # Aman
for roll, name, m in S:
print(name, m)Nested tuples store fixed tables, like records that should not change by mistake.
List vs tuple
| List | Tuple |
|---|---|
| [ ] | ( ) |
| Mutable | Immutable |
| Many methods (append, sort…) | Only count() and index() |
| For data that changes | For fixed data; a bit faster and safer |
Key formulas and definitions
- Single item: (5,)
- Tuples are immutable: T[i] = x → TypeError
- Methods: count(), index(); functions: len, min, max, sum, sorted
- Unpacking: a, b = (3, 8) · Swap: a, b = b, a
- Nested: S[row][col]
Worked examples
1. T = (10, 20, 30, 40). Find T[1:3], T[-1], T + (50,), 25 in T.
(20, 30); 40; (10, 20, 30, 40, 50); False.
2. What is type((5)) and type((5,))?
type((5)) is int (brackets only group); type((5,)) is tuple.
3. Output? T = (3, 1, 3, 2); print(T.count(3), T.index(2), sorted(T))
2 3 [1, 2, 3, 3]
4. Swap x = 5 and y = 9 using a tuple.
x, y = y, x → x = 9, y = 5.
5. Find max and min in a tuple of marks entered by the user.
T = tuple(int(x) for x in input().split()) # or build a list then tuple() print(max(T), min(T))
6. S = ((1, 'Riya', 91), (2, 'Aman', 85)). Print the average marks.
total = 0 for r in S: total += r[2] print(total / len(S)) # 88.0
Common mistakes
- Writing (5) for a one-item tuple. Use (5,).
- Calling T.append(3) or T.sort(). Tuples have no such methods.
- Unpacking the wrong number of values: a, b = (1, 2, 3) gives ValueError.
- Thinking sorted(T) returns a tuple. It returns a list; use tuple(sorted(T)).