Some data should NEVER change once it's created โ the days of the week, the months of a year, the latitude and longitude of your school, or your date of birth. If you store such data in a list, a single wrong line of code could accidentally change it. Python gives us a safer container for this: the tuple. A tuple looks and behaves a lot like a list, but it is locked after creation. This chapter shows how to create a tuple (and why (5) is not one), which operations and functions work on tuples, what packing and unpacking mean, and when to choose a tuple instead of a list.
Focus especially on creating a single-element tuple, tuple immutability (and the "list inside a tuple" trick), packing and unpacking, tuple functions (count, index, sorted, min, max, sum), and List vs Tuple โ revise these carefully.
11.1 ๐ Introduction
A tuple is an ordered, immutable collection of values enclosed in round brackets ( ) and separated by commas. Like lists, tuples can hold values of different data types and allow duplicates.
days = ("Mon", "Tue", "Wed", "Thu", "Fri") # tuple of strings
point = (10, 20) # a pair of numbers
student = (101, "Riya", 92.5, True) # mixed types
empty = () # an empty tuple
nested = (1, 2, (3, 4), [5, 6]) # tuple containing a tuple and a list
Ordered
Elements keep their order and are accessed by index
IndexedImmutable
Elements CANNOT be changed, added or removed after creation
Read-onlyHeterogeneous
One tuple can hold values of different types
int with str with floatDuplicates Allowed
The same value can appear more than once
(1 1 2) is validAnalogy: A list is like a whiteboard โ you can write, erase and rewrite. A tuple is like a printed certificate ๐ โ once printed, nobody can change the name or the marks on it. You can read it as many times as you like, but you can't edit it!
11.2 ๐ ๏ธ Creating Tuples
11.2.1 Different Ways to Create a Tuple
T1 = (1, 2, 3) # using round brackets
T2 = 4, 5, 6 # brackets are optional โ commas make the tuple!
T3 = tuple([7, 8, 9]) # from a list
T4 = tuple("ABC") # from a string โ ('A', 'B', 'C')
T5 = tuple(range(1, 4)) # from a range โ (1, 2, 3)
T6 = tuple() # empty tuple โ ()
print(T2, type(T2)) # (4, 5, 6) <class 'tuple'>
print(T4) # ('A', 'B', 'C')
11.2.2 The Single-Element Tuple Trap โ ๏ธ
This is a classic tuple question.
a = (5)
b = (5,)
c = 5,
print(type(a)) # <class 'int'> โ NOT a tuple!
print(type(b)) # <class 'tuple'>
print(type(c)) # <class 'tuple'>
print(b) # (5,)
It is the comma, not the brackets, that creates a tuple. (5) is just the number 5 inside ordinary maths brackets. To create a tuple with one element, you MUST put a trailing comma: (5,).
"What is the difference between T = (10) and T = (10,)?" โ 1-mark question, asked very often!
Answer: T = (10) creates an integer (the brackets are just grouping brackets), whereas T = (10,) creates a tuple with one element, because the comma makes it a tuple.
11.2.3 Taking a Tuple as Input
# Method 1: the user types the tuple itself, e.g. (10, 20, 30)
T = eval(input("Enter a tuple: "))
# Method 2: build a list first, then convert it
L = []
n = int(input("How many elements? "))
for i in range(n):
L.append(int(input("Enter element: ")))
T = tuple(L)
print(T)
11.3 ๐ข Accessing Tuple Elements
11.3.1 Indexing
Tuples use the same two-way indexing as strings and lists:
T = ( 'a', 'e', 'i', 'o', 'u' )
Forward: 0 1 2 3 4
Backward: -5 -4 -3 -2 -1
T = ('a', 'e', 'i', 'o', 'u')
print(T[0], T[2], T[-1]) # a i u
print(len(T)) # 5
# print(T[5]) # โ IndexError: tuple index out of range
11.3.2 Traversing a Tuple
T = (12, 45, 7, 30)
for x in T:
print(x, end=" ")
# Output: 12 45 7 30
for i in range(len(T)):
print("Index", i, "โ", T[i])
11.3.3 Tuples are Immutable ๐
T = (10, 20, 30)
# T[0] = 100 # โ TypeError: 'tuple' object does not support item assignment
# T.append(40) # โ AttributeError: 'tuple' object has no attribute 'append'
# del T[0] # โ TypeError: 'tuple' object doesn't support item deletion
del T # โ
allowed โ deletes the WHOLE tuple variable
# print(T) # โ NameError: name 'T' is not defined
To "change" a tuple, you must create a new tuple:
T = (10, 20, 30)
T = T + (40,) # a NEW tuple is created and assigned to T
print(T) # (10, 20, 30, 40)
T = (10, 20, 30)
L = list(T) # convert to a list
L[1] = 200 # change the list
T = tuple(L) # convert back
print(T) # (10, 200, 30)
A tuple cannot be changed โ but if one of its elements is a mutable object (like a list), that object can still be changed!
T = (1, 2, [3, 4])
T[2][0] = 30 # โ
allowed โ we are changing the LIST, not the tuple
print(T) # (1, 2, [30, 4])
# T[2] = [5, 6] # โ TypeError โ replacing the element itself is not allowed
The tuple still holds the same list object; only the contents of that list changed.
11.4 โ Tuple Operations
| Operation | Example | Result |
|---|---|---|
Concatenation + |
(1, 2) + (3, 4) |
(1, 2, 3, 4) |
Replication * |
("Hi",) * 3 |
('Hi', 'Hi', 'Hi') |
Membership in |
3 in (1, 2, 3) |
True |
Membership not in |
"z" not in ("a", "b") |
True |
Comparison == |
(1, 2) == (1, 2) |
True |
Comparison < |
(1, 2, 5) < (1, 3) |
True (2 < 3 at index 1) |
T = (1, 2)
# T + 3 # โ TypeError: can only concatenate tuple (not "int") to tuple
print(T + (3,)) # โ
(1, 2, 3)
11.4.1 Slicing โ๏ธ
Slicing works exactly as for strings and lists โ T[start : stop : step] โ and it always returns a new tuple.
T = ( 10, 20, 30, 40, 50, 60 )
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
| Slice | Result |
|---|---|
T[1:4] |
(20, 30, 40) |
T[:2] |
(10, 20) |
T[-3:] |
(40, 50, 60) |
T[::2] |
(10, 30, 50) |
T[::-1] |
(60, 50, 40, 30, 20, 10) |
T[4:1:-1] |
(50, 40, 30) |
T[2:3] |
(30,) โ still a tuple! |
T[2] gives the element 30 (an int), but T[2:3] gives a tuple (30,). Indexing returns one element; slicing ALWAYS returns a tuple.
11.5 ๐ฆ Tuple Assignment โ Packing and Unpacking
11.5.1 Packing
Packing means putting several values together into a tuple.
student = 101, "Aman", 88 # the three values are PACKED into one tuple
print(student) # (101, 'Aman', 88)
11.5.2 Unpacking
Unpacking means extracting the values of a tuple into separate variables in one statement. The number of variables on the left must equal the number of elements.
student = (101, "Aman", 88)
roll, name, marks = student # UNPACKING
print(name) # Aman
print(marks) # 88
student = ( 101 , "Aman" , 88 )
โ โ โ
roll, name, marks = 101, "Aman", 88
The counts must match exactly! a, b = (1, 2, 3) gives ValueError: too many values to unpack, and a, b, c = (1, 2) gives ValueError: not enough values to unpack.
11.5.3 Swapping Using Tuple Assignment ๐
The famous one-line swap you saw earlier is actually packing + unpacking!
a, b = 5, 10
a, b = b, a # right side packs (10, 5); left side unpacks it
print(a, b) # 10 5
"What is tuple unpacking? Explain with an example." โ 2-mark question!
Answer: Unpacking is assigning the elements of a tuple to an equal number of variables in a single statement. Example: t = (3, 4, 5) and x, y, z = t gives x = 3, y = 4, z = 5. The number of variables must equal the number of elements.
11.6 ๐งฐ Tuple Functions and Methods
Because tuples are immutable, they have only two methods: count() and index(). All other operations are done with built-in functions.
| Function / Method | Description | Example (T = (4, 9, 1, 9, 7)) |
Result |
|---|---|---|---|
len(T) |
Number of elements | len(T) |
5 |
T.count(x) |
Number of times x occurs |
T.count(9) |
2 |
T.index(x) |
Index of the first occurrence of x; ValueError if absent |
T.index(9) |
1 |
max(T) |
Largest element | max(T) |
9 |
min(T) |
Smallest element | min(T) |
1 |
sum(T) |
Sum of the elements (numbers only) | sum(T) |
30 |
sorted(T) |
Returns a new sorted LIST (not a tuple!) | sorted(T) |
[1, 4, 7, 9, 9] |
tuple(seq) |
Converts a sequence into a tuple | tuple([1, 2]) |
(1, 2) |
T = (40, 10, 30, 20)
S = sorted(T)
print(S, type(S)) # [10, 20, 30, 40] <class 'list'>
print(tuple(sorted(T))) # (10, 20, 30, 40)
print(sorted(T, reverse=True)) # [40, 30, 20, 10]
print(T) # (40, 10, 30, 20) โ unchanged
sorted() returns a list, even when you give it a tuple. Wrap it in tuple() if you need a tuple back. And tuples have NO sort(), append(), insert(), remove() or pop() methods โ calling them gives an AttributeError.
A tuple is a read-only object, so its only methods are the two that read it: count() and index() โ think "C-I: Can't Interfere!" ๐
11.7 ๐ช Nested Tuples
A tuple can contain other tuples โ useful for fixed, table-like data.
results = (("Riya", 92), ("Aman", 85), ("Zoya", 78))
print(results[1]) # ('Aman', 85)
print(results[1][0]) # Aman
for name, marks in results: # unpacking inside the loop!
print(name, "scored", marks)
Riya scored 92
Aman scored 85
Zoya scored 78
11.8 โ๏ธ List vs Tuple
| Feature | List | Tuple |
|---|---|---|
| Brackets | Square [ ] |
Round ( ) (or just commas) |
| Mutability | โ Mutable โ can be changed | โ Immutable โ cannot be changed |
| Methods | Many (append, insert, sort, pop โฆ) |
Only count() and index() |
| Speed | Slightly slower | Slightly faster to create and traverse |
| Safety | Data can be changed by mistake | Data is protected from changes |
| Single element | [5] |
(5,) โ comma needed |
| Use when | Data will change (shopping cart, marks being entered) | Data must stay fixed (days of the week, coordinates) |
Data Safety
Values like months or constants can't be changed by mistake
Read-only dataFaster
Python can create and loop over tuples slightly faster than lists
Better performanceDictionary Keys
Tuples (of immutable values) can be used as dictionary keys; lists cannot
You'll see this next chapterMultiple Values
Packing and unpacking make it easy to handle several values at once
One-line swap"Differentiate between a list and a tuple." โ 2-mark question.
Answer: A list is mutable โ its elements can be changed, added or removed โ and is written in square brackets [ ]. A tuple is immutable โ its elements cannot be changed after creation โ and is written in round brackets ( ). Lists have many methods; tuples have only count() and index().
11.9 ๐ป Important Tuple Programs
Code Example: tuple_stats.py
# Find the maximum, minimum and mean of numbers in a tuple
T = (45, 12, 78, 34, 89, 23)
largest = smallest = T[0]
total = 0
for x in T:
if x > largest:
largest = x
if x < smallest:
smallest = x
total += x
print("Maximum:", largest)
print("Minimum:", smallest)
print("Mean:", round(total / len(T), 2))
Maximum: 89
Minimum: 12
Mean: 46.83
Code Example: tuple_search.py
# Linear search in a tuple
T = (15, 8, 42, 23, 4, 16)
key = int(input("Enter the value to search: "))
found = False
for i in range(len(T)):
if T[i] == key:
print(key, "found at index", i)
found = True
break
if not found:
print(key, "is not in the tuple")
# Input 23 โ 23 found at index 3
# Input 99 โ 99 is not in the tuple
Code Example: tuple_frequency.py
# Count the frequency of each element in a tuple
T = ("a", "b", "a", "c", "b", "a")
seen = ()
for x in T:
if x not in seen:
print(x, ":", T.count(x))
seen = seen + (x,)
a : 3
b : 2
c : 1
Code Example: even_odd_tuple.py
# Create two new tuples of even and odd numbers from a given tuple
T = (11, 24, 35, 46, 57, 68)
even = odd = ()
for x in T:
if x % 2 == 0:
even += (x,)
else:
odd += (x,)
print("Even:", even) # Even: (24, 46, 68)
print("Odd:", odd) # Odd: (11, 35, 57)
Code Example: fibonacci_tuple.py
# Store the first n Fibonacci numbers in a tuple
n = int(input("How many terms? "))
fib = ()
a, b = 0, 1
for i in range(n):
fib += (a,)
a, b = b, a + b
print(fib)
# Input 7 โ (0, 1, 1, 2, 3, 5, 8)
"Find max/min/mean", "linear search" and "frequency of elements" are suggested practical programs for tuples in the CBSE syllabus. Remember: since a tuple can't be changed, "adding" an element means creating a new tuple with T = T + (x,) โ don't forget the comma!
โ ๏ธ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
โ T = (5) makes a tuple |
Brackets alone don't make a tuple | โ
T = (5,) โ the comma makes it a tuple |
โ T[0] = 10 changes a tuple |
Tuples are immutable | โ TypeError; create a new tuple instead |
โ T.append(4) / T.sort() |
Tuples have no such methods | โ
AttributeError; only count() and index() exist |
โ sorted(T) returns a tuple |
sorted() always returns a list | โ
Use tuple(sorted(T)) |
โ T + 5 adds an element |
Can't join a tuple and an int | โ
T + (5,) |
| โ Nothing inside a tuple can ever change | A mutable element can change | โ
In (1, [2, 3]), the list can be modified |
โ del T[1] deletes an element |
Item deletion not allowed | โ
Only del T (the whole tuple) works |
โ a, b = (1, 2, 3) |
Counts don't match | โ ValueError; the numbers of variables and values must be equal |
โ T[2:3] gives an element |
Slicing returns a tuple | โ
It gives (value,) |
๐ Quick Revision
Tuple Basics:
- Ordered, immutable collection in
( ); the comma makes the tuple - Single element:
(5,)ยท Empty:()ortuple() - Indexing, slicing,
+,*,in, comparison โ same as lists (slices give tuples) - "Change" = create a new tuple, or convert โ list โ change โ tuple
Packing and Unpacking:
- Packing:
t = 1, 2, 3 - Unpacking:
a, b, c = t(counts must match) - Swap:
a, b = b, a
Functions and Methods:
| Only 2 methods | Built-in functions |
|---|---|
count(x), index(x) |
len(), max(), min(), sum(), sorted() โ list, tuple() |
List vs Tuple: List โ [ ], mutable, many methods ยท Tuple โ ( ), immutable, faster, safer, can be a dictionary key
๐ฏ Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) What is the type of x in x = (7)?
โ int
b) Name the only two methods available for tuples.
โ count() and index()
c) What is the output of print((1, 2) * 2)?
โ (1, 2, 1, 2)
d) What does sorted((3, 1, 2)) return?
โ [1, 2, 3] (a list)
e) What is the output of print(len((1, (2, 3), [4, 5, 6])))?
โ 3
Q2: Output Based [2 marks]
Q: Write the output of the following code:
T = (10, 20, 30, 40, 50)
print(T[1:4], T[-2], T[::-2])
a, b, c = T[:3]
print(a + b + c, T.index(c))
Answer:
(20, 30, 40) 40 (50, 30, 10)
60 2
(T[:3] is (10, 20, 30), which is unpacked into a, b and c.)
Q3: Find the Errors [2 marks]
Q: Identify the errors (if any) in the following code and explain why:
T = (5, 10, 15)
T[1] = 12
T.append(20)
print(T + 25)
Answer:
T[1] = 12โ TypeError: a tuple does not support item assignment (it is immutable).T.append(20)โ AttributeError: tuples have noappend()method.T + 25โ TypeError: a tuple can only be concatenated with another tuple; writeT + (25,).
Q4: Output Based [3 marks]
Q: Write the output of the following code:
T1 = (1, 2, [3, 4])
T1[2].append(5)
print(T1)
T2 = T1[:2] + (6,)
print(T2, len(T2))
T3 = ("A",) * 2 + ("B",)
print(T3, T3.count("A"), T3.index("B"))
Answer:
(1, 2, [3, 4, 5])
(1, 2, 6) 3
('A', 'A', 'B') 2 2
Q5: Program [3 marks]
Q: Write a program to input a tuple of numbers and create a new tuple that contains only the elements greater than the mean of the tuple.
T = eval(input("Enter a tuple of numbers: "))
mean = sum(T) / len(T)
result = ()
for x in T:
if x > mean:
result += (x,)
print("Mean:", mean)
print("Elements above mean:", result)
# Input (10, 20, 30, 40, 50) โ Mean: 30.0
# Elements above mean: (40, 50)
โ๏ธ Practice Problems
-
Differentiate between a list and a tuple (any four points).
-
Write the output of: (a)
type((1))(b)type((1,))(c)tuple("CS")(d)(1, 2) + (3,) * 2 -
If
T = ('P', 'Y', 'T', 'H', 'O', 'N'), write the output of: (a)T[2:5](b)T[-1:-4:-1](c)T.index('H')(d)'y' in T -
Explain packing and unpacking with one example each.
-
Write a program to input a tuple of strings and print the longest string along with its length.
-
Write a program to input a tuple of integers and count how many are positive, negative and zero.
-
Write a program to input two tuples and create a third tuple containing the elements common to both (without duplicates).
-
"A tuple is immutable, yet the following code works." Explain why:
T = ([1, 2], 3); T[0].append(9) -
Write a program to store the names of the 7 days of the week in a tuple and print the days that have more than 6 letters.
-
Write a program to find the second largest element of a tuple without using
sorted().