CHAPTER PDF
Complete curriculum textbook chapter document for reading and offline study.
NOTES
Complete conceptual breakdown, formulas, diagrams, and memory aids.
Chapter 10: Tuples and Dictionaries
Complete learning notes with concepts, Python syntax, worked examples, textbook programs, outputs, solved exercises and programming practice.
Learning overview
This chapter introduces two important Python collection types: tuples, which are immutable ordered sequences, and dictionaries, which store data as key–value mappings.
After studying tuples, you should be able to
- Create empty, single-element and mixed tuples.
- Access elements using positive/negative indexing and slicing.
- Apply concatenation, repetition and membership.
- Use tuple functions, unpacking and nested tuples.
- Return multiple values from a function.
After studying dictionaries, you should be able to
- Create and access key–value pairs.
- Add, update and delete dictionary items.
- Traverse keys, values and items.
- Use dictionary methods and built-in functions.
- Build small data-management programs.
10.1 Introduction to Tuples
A tuple is an ordered sequence of elements. Its elements may belong to different data types, such as integers, floats, strings, lists or even other tuples. Tuple elements are normally written inside round brackets () and separated by commas.
Basic syntax
tuple_name = (element1, element2, element3, ...)
Examples
# Tuple containing integers
tuple1 = (1, 2, 3, 4, 5)
# Tuple containing mixed data types
tuple2 = ('Economics', 87, 'Accountancy', 89.6)
# A list can be an element of a tuple
tuple3 = (10, 20, 30, [40, 50])
# A tuple can contain another tuple
tuple4 = (1, 2, 3, 4, 5, (10, 20))
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)
(1, 2, 3, 4, 5)
('Economics', 87, 'Accountancy', 89.6)
(10, 20, 30, [40, 50])
(1, 2, 3, 4, 5, (10, 20))
Creating an empty tuple
t1 = ()
t2 = tuple()
print(t1) # ()
print(t2) # ()
Single-element tuple: the comma is essential
A one-element tuple must contain a trailing comma. Without the comma, Python treats the expression as the element itself, not as a tuple.
# Not a tuple: this is an integer
value = (20)
print(type(value)) # <class 'int'>
# Correct: one-element tuple
single = (20,)
print(single) # (20,)
print(type(single)) # <class 'tuple'>
Tuple without parentheses (tuple packing)
A comma-separated sequence can be treated as a tuple even when parentheses are omitted.
seq = 1, 2, 3
print(seq) # (1, 2, 3)
print(type(seq)) # <class 'tuple'>
Tuple and list: when are they used?
The chapter notes that lists are commonly used for elements of the same type that may need modification, while tuples are useful for grouping related values, often of different types, when the collection should remain fixed.
10.1.1 Accessing Elements in a Tuple
Tuple elements are accessed in the same way as list and string elements: by indexing or slicing. Indexing starts at zero.
tuple1 = (2, 4, 6, 8, 10, 12)
print(tuple1[0]) # first element: 2
print(tuple1[3]) # fourth element: 8
print(tuple1[1 + 4]) # index 5: 12
print(tuple1[-1]) # last element: 12
2
8
12
12
| Index type | Meaning | Example | Result |
|---|---|---|---|
| Positive | Counts from left, starting at 0 | tuple1[0] | 2 |
| Positive | Fourth element | tuple1[3] | 8 |
| Negative | Counts from right, starting at -1 | tuple1[-1] | 12 |
tuple1[15] raises IndexError: tuple index out of range.10.1.2 Tuple is Immutable
Immutable means that the tuple's element references cannot be reassigned after the tuple is created. You cannot replace, add or remove a tuple element directly.
tuple1 = (1, 2, 3, 4, 5)
tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment
A mutable object inside an immutable tuple
A tuple can contain a mutable object such as a list. The tuple's element cannot be replaced, but the contents of that inner list can be modified.
tuple2 = (1, 2, 3, [8, 9])
# Modify the list stored at index 3
tuple2[3][1] = 10
print(tuple2)(1, 2, 3, [8, 10])
The tuple still refers to the same list object; the list's contents have changed. This is why “tuple is immutable” does not mean every object reachable through a tuple is immutable.
Why use tuples?
- They protect the sequence structure from accidental item reassignment.
- They are suitable for fixed records, such as a coordinate or a student's fixed record.
- The textbook notes that iteration through a tuple can be faster than through a list in the discussed context; actual performance depends on the operation and Python implementation.
10.2 Tuple Operations
10.2.1 Concatenation (+)
Concatenation joins two tuples and produces a new tuple. It does not modify either original tuple.
tuple1 = (1, 3, 5, 7, 9)
tuple2 = (2, 4, 6, 8, 10)
tuple3 = tuple1 + tuple2
print(tuple3)(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Concatenation can also be used to extend a tuple. To append one element, use a one-element tuple with a comma.
tuple6 = (1, 2, 3, 4, 5)
tuple6 = tuple6 + (6,)
print(tuple6)
tuple6 = tuple6 + (7, 8, 9)
print(tuple6)(1, 2, 3, 4, 5, 6)
(1, 2, 3, 4, 5, 6, 7, 8, 9)
10.2.2 Repetition (*)
The repetition operator repeats the tuple's elements. The left operand must be a tuple and the repeat count must be an integer.
tuple1 = ('Hello', 'World')
print(tuple1 * 3)
tuple2 = ('Hello',)
print(tuple2 * 4)('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
('Hello', 'Hello', 'Hello', 'Hello')
10.2.3 Membership (in and not in)
in checks whether an element is present. not in checks whether it is absent. Both return Boolean values: True or False.
colours = ('Red', 'Green', 'Blue')
print('Green' in colours)
print('Green' not in colours)
print('Black' in colours)True
False
False
10.2.4 Slicing
Slicing extracts a portion of a tuple and returns a new tuple.
tuple1 = (10, 20, 30, 40, 50, 60, 70, 80)
print(tuple1[2:7]) # index 2 through 6
print(tuple1[0:len(tuple1)])# complete tuple
print(tuple1[:5]) # beginning through index 4
print(tuple1[2:]) # index 2 through end
print(tuple1[0:len(tuple1):2]) # step size 2
print(tuple1[-6:-4]) # negative indices
print(tuple1[::-1]) # reverse order
(30, 40, 50, 60, 70)
(10, 20, 30, 40, 50, 60, 70, 80)
(10, 20, 30, 40, 50)
(30, 40, 50, 60, 70, 80)
(10, 30, 50, 70)
(30, 40)
(80, 70, 60, 50, 40, 30, 20, 10)
tuple_name[start : stop : step]. The start index is included; the stop index is excluded. If omitted, start defaults to the beginning, stop to the end, and step to 1.10.3 Tuple Methods and Built-in Functions
The tuple type has two commonly used methods, count() and index(). Other operations in the table are built-in functions.
| Function / method | Purpose | Example and result |
|---|---|---|
len(t) | Returns number of elements. | len((10,20,30)) → 3 |
tuple() | Creates an empty tuple or converts an iterable into a tuple. | tuple('aeiou') → ('a','e','i','o','u') |
count(x) | Counts occurrences of x. | (10,20,10).count(10) → 2 |
index(x) | Returns index of first occurrence of x. | (10,20,30).index(30) → 2 |
sorted(t) | Returns a new sorted list; original tuple is unchanged. | sorted((3,1,2)) → [1,2,3] |
min(t) | Returns smallest element. | min((19,12,56,9)) → 9 |
max(t) | Returns largest element. | max((19,12,56,87)) → 87 |
sum(t) | Returns sum of numeric elements. | sum((19,12,56)) → 87 |
Worked examples
t = (10, 20, 30, 10, 40, 10, 50)
print(len(t)) # 7
print(t.count(10)) # 3
print(t.index(30)) # 2
print(min(t)) # 10
print(max(t)) # 50
print(sum(t)) # 170
names = ('Rama', 'Heena', 'Raj', 'Mohsin', 'Aditya')
print(sorted(names))7
3
2
10
50
170
['Aditya', 'Heena', 'Mohsin', 'Raj', 'Rama']
index(x) raises ValueError if x is absent. sorted() returns a list, not a tuple. sum() is intended for numeric values.10.4 Tuple Assignment
Tuple assignment (also called unpacking) assigns values from a sequence to multiple variables in one statement. The number of target variables must match the number of values being unpacked.
(num1, num2) = (10, 20)
print(num1) # 10
print(num2) # 20
record = ('Pooja', 40, 'CS')
(name, rollNo, subject) = record
print(name) # Pooja
print(rollNo) # 40
print(subject) # CS
Unpacking count must match
(a, b, c, d) = (5, 6, 8)ValueError: not enough values to unpack (expected 4, got 3)
Expressions on the right side
Python evaluates the right-hand expressions first, then assigns the resulting values.
(num3, num4) = (10 + 5, 20 + 5)
print(num3) # 15
print(num4) # 25
a, b = b, a swaps two variables without requiring a temporary variable. Python evaluates the right-hand side before assigning to the left-hand side.10.5 Nested Tuples
A nested tuple is a tuple that contains one or more tuples as its elements. It is useful for storing multiple fixed records. In the textbook example, each student record contains roll number, name and marks.
Program 10-1: Store student records in a nested tuple
# Store roll number, name and marks of students
st = (
(101, "Aman", 98),
(102, "Geet", 95),
(103, "Sahil", 87),
(104, "Pawan", 79)
)
print("S_No", "Roll_No", "Name", "Marks")
for i in range(len(st)):
print(i + 1, st[i][0], st[i][1], st[i][2], sep="\\t")
S_No Roll_No Name Marks
1 101 Aman 98
2 102 Geet 95
3 103 Sahil 87
4 104 Pawan 79
Understanding the nested indexing
st[0]gives the first student's tuple:(101, "Aman", 98).st[0][0]gives the first student's roll number:101.st[0][1]gives the first student's name:"Aman".st[0][2]gives the first student's marks:98.
\\t inserts a horizontal tab; \\n inserts a new line.10.6 Tuple Handling
Program 10-2: Swap two numbers without a temporary variable
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("\\nNumbers before swapping:")
print("First Number:", num1)
print("Second Number:", num2)
(num1, num2) = (num2, num1)
print("\\nNumbers after swapping:")
print("First Number:", num1)
print("Second Number:", num2)Enter the first number: 5
Enter the second number: 10
Numbers before swapping:
First Number: 5
Second Number: 10
Numbers after swapping:
First Number: 10
Second Number: 5
Program 10-3: Return area and circumference of a circle
A Python function can return more than one value. The values are returned together as a tuple and can be unpacked into separate variables.
def circle(r):
area = 3.14 * r * r
circumference = 2 * 3.14 * r
return (area, circumference)
radius = float(input("Enter radius of circle: "))
area, circumference = circle(radius)
print("Area of circle is:", area)
print("Circumference of circle is:", circumference)Enter radius of circle: 5
Area of circle is: 78.5
Circumference of circle is: 31.4
Program 10-4: Input n numbers into a tuple; display maximum and minimum
numbers = tuple()
n = int(input("How many numbers do you want to enter? "))
for i in range(n):
num = int(input("Enter a number: "))
numbers = numbers + (num,)
print("The numbers in the tuple are:")
print(numbers)
print("The maximum number is:", max(numbers))
print("The minimum number is:", min(numbers))How many numbers do you want to enter? 5
Enter a number: 9
Enter a number: 8
Enter a number: 10
Enter a number: 12
Enter a number: 15
The numbers in the tuple are: (9, 8, 10, 12, 15)
The maximum number is: 15
The minimum number is: 8
max() and min() require at least one value. If the user enters 0, the tuple is empty and these functions raise ValueError. A production version should validate that n is greater than zero.10.7 Introduction to Dictionaries
A dictionary is a mapping data type. It stores information as key–value pairs. Each pair is called an item. A colon separates a key from its value, and commas separate consecutive items.
Dictionary syntax uses curly braces {}. Each key must be unique. Keys must be hashable; at this level, the textbook describes them as immutable types such as numbers, strings or tuples. Values may be of any data type and may be repeated.
{'Mohan': 95, 'Ram': 89} means that the key 'Mohan' maps to the value 95, and the key 'Ram' maps to 89.10.7.1 Creating a Dictionary
# Empty dictionary using {}
dict1 = {}
# Empty dictionary using dict()
dict2 = dict()
# Dictionary with student names and marks
dict3 = {
'Mohan': 95,
'Ram': 89,
'Suhel': 92,
'Sangeeta': 85
}
print(dict1)
print(dict2)
print(dict3){}
{}
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
Rules for dictionary keys and values
| Property | Keys | Values |
|---|---|---|
| Uniqueness | Must be unique | May be repeated |
| Data type | Must be hashable (e.g. int, str, suitable tuple) | Any data type |
| Purpose | Used to locate a value | Stores the associated data |
{} creates an empty dictionary, not an empty set. An empty set is created using set().10.7.2 Accessing Items in a Dictionary
Unlike strings, lists and tuples, dictionary items are accessed using keys rather than numeric positions. Each key maps to its corresponding value.
dict3 = {
'Mohan': 95,
'Ram': 89,
'Suhel': 92,
'Sangeeta': 85
}
print(dict3['Ram'])
print(dict3['Sangeeta'])89
85
What happens if a key is missing?
print(dict3['Shyam'])KeyError: 'Shyam'
Square-bracket lookup raises KeyError if the key does not exist. The get() method, explained later, can be used when a missing key should return None or a default value instead.
10.8 Dictionaries are Mutable
Dictionaries are mutable, which means their contents can be changed after creation.
10.8.1 Adding a new item
Assign a value to a key that does not yet exist. Python adds a new key–value pair.
dict1 = {
'Mohan': 95,
'Ram': 89,
'Suhel': 92,
'Sangeeta': 85
}
dict1['Meena'] = 78
print(dict1){'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78}
10.8.2 Modifying an existing item
Assign a new value to an existing key. The key remains the same; its associated value is replaced.
dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
# Update Suhel's marks
dict1['Suhel'] = 93.5
print(dict1){'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85}
10.9 Dictionary Operations
10.9.1 Membership
The in and not in operators check dictionary keys, not values.
dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
print('Suhel' in dict1)
print('Suhel' not in dict1)
print(92 in dict1)True
False
False
92 in dict1 is False because 92 is a value, not a key. To test values, use 92 in dict1.values().10.10 Traversing a Dictionary
Traversing means visiting each dictionary item one by one. A for loop can be used.
Method 1: Iterate over keys
dict1 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
for key in dict1:
print(key, ':', dict1[key])Mohan : 95
Ram : 89
Suhel : 92
Sangeeta : 85
Method 2: Iterate over key–value pairs using items()
for key, value in dict1.items():
print(key, ':', value)Mohan : 95
Ram : 89
Suhel : 92
Sangeeta : 85
Method 2 is often convenient because the key and value are unpacked directly into two variables.
10.11 Dictionary Methods and Built-in Functions
| Method / function | Purpose | Example |
|---|---|---|
len(d) | Returns number of key–value pairs. | len({'A':1,'B':2}) → 2 |
dict() | Creates a dictionary, including from key–value pair sequences. | dict([('A',1),('B',2)]) → {'A':1,'B':2} |
keys() | Returns a view of all keys. | d.keys() |
values() | Returns a view of all values. | d.values() |
items() | Returns a view of key–value pairs as tuples. | d.items() |
get(key) | Returns the value for key; returns None if missing unless a default is supplied. | d.get('A') |
update(other) | Adds items from another mapping; matching keys are overwritten. | d.update({'C':3}) |
del d[key] | Deletes the item with the given key. | del d['A'] |
clear() | Removes all items, leaving an empty dictionary. | d.clear() |
Detailed examples
d = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
print(len(d)) # 4
print(d.keys()) # dict_keys([...])
print(d.values()) # dict_values([...])
print(d.items()) # dict_items([...])
print(d.get('Sangeeta')) # 85
print(d.get('Sohan')) # None
print(d.get('Sohan', 0)) # 0 (custom default)
Creating a dictionary using dict()
pair1 = [
('Mohan', 95),
('Ram', 89),
('Suhel', 92),
('Sangeeta', 85)
]
dict1 = dict(pair1)
print(dict1){'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
Using update()
dict1 = {'Mohan': 95, 'Ram': 89}
dict2 = {'Suhel': 92, 'Geeta': 89}
dict1.update(dict2)
print(dict1)
print(dict2) # original dict2 remains available{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Geeta': 89}
{'Suhel': 92, 'Geeta': 89}
Deleting items: del and clear()
d = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
del d['Ram'] # delete one key-value pair
print(d)
d.clear() # remove all items
print(d) # {}{'Mohan': 95, 'Suhel': 92, 'Sangeeta': 85}
{}
del d['A'] removes one item. del d deletes the dictionary variable itself; using it afterwards causes NameError. d.clear() empties the dictionary but the variable still exists.10.12 Manipulating Dictionaries
Program 10-5: Dictionary of odd numbers and their names
Create a dictionary where each key is an odd number between 1 and 10 and each value is its number name. Display keys, values, items, length, membership, retrieve key 9 and delete key 9.
ODD = {1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}
# (a) Display keys
print(ODD.keys())
# (b) Display values
print(ODD.values())
# (c) Display items
print(ODD.items())
# (d) Length
print(len(ODD))
# (e) Is key 7 present?
print(7 in ODD)
# (f) Is key 2 present?
print(2 in ODD)
# (g) Retrieve value for key 9
print(ODD.get(9))
# (h) Delete key 9
del ODD[9]
print(ODD)
Length: 5
7 in ODD: True
2 in ODD: False
ODD.get(9): Nine
After deletion: {1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}
Program 10-6: Store employee names and salaries
num = int(input("Enter the number of employees: "))
employee = {}
count = 1
while count <= num:
name = input("Enter the name of the employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\\nEMPLOYEE_NAME\\tSALARY")
for name in employee:
print(name, employee[name], sep="\\t\\t")
Explanation: The program creates an empty dictionary. Each employee's name is used as a key and salary as its value. The loop repeats for the number of employees entered. The final loop displays each key and its corresponding value.
Program 10-7: Count frequency of each character in a string
st = input("Enter a string: ")
dic = {}
for ch in st:
if ch in dic:
dic[ch] += 1
else:
dic[ch] = 1
for key in dic:
print(key, ':', dic[key])Enter a string: HelloWorld
H : 1
e : 1
l : 3
o : 2
W : 1
r : 1
d : 1
Logic: For each character, check whether it already exists as a key. If it exists, increase its count by one. Otherwise, create the key with initial count 1. Uppercase and lowercase characters are counted separately; spaces and punctuation are also counted if present.
Program 10-8: Convert each digit of a number into words
def convert(num):
numberNames = {
0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three',
4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven',
8: 'Eight', 9: 'Nine'
}
result = ''
for ch in num:
key = int(ch)
value = numberNames[key]
result = result + ' ' + value
return result.strip()
num = input("Enter any number: ")
result = convert(num)
print("The number is:", num)
print("The numberName is:", result)Enter any number: 6512
The number is: 6512
The numberName is: Six Five One Two
007 becomes “Zero Zero Seven”). This program converts digits individually, not the whole number into conventional number wording.Chapter Summary
- A tuple is an ordered, immutable sequence. Its elements are comma-separated and commonly enclosed in round brackets.
- A single-element tuple requires a trailing comma, for example
(5,). - Tuple elements can be accessed using positive/negative indexing and slicing.
- Tuple operations include concatenation (
+), repetition (*), membership (in,not in) and slicing. - Tuple functions/methods include
len(),tuple(),count(),index(),sorted(),min(),max()andsum(). - Tuple assignment unpacks a sequence into variables; it can also swap two variables.
- A nested tuple contains another tuple. A function can return multiple values as a tuple.
- A dictionary maps unique keys to values. It is written using curly braces and colon-separated key–value pairs.
- Dictionary values may be repeated and may be mutable. Keys must be unique and hashable.
- Dictionary items are accessed using keys, not numeric positions.
- Dictionaries are mutable: items can be added, modified and deleted.
- Dictionary traversal can be performed using a
forloop anditems(). - Dictionary methods include
keys(),values(),items(),get(),update()andclear();delremoves a key or variable.
Tuple vs Dictionary vs List
| Feature | List | Tuple | Dictionary |
|---|---|---|---|
| Structure | Sequence | Sequence | Key–value mapping |
| Syntax | [] | () / commas | {key: value} |
| Access | Index | Index | Key |
| Mutable? | Yes | No (tuple structure) | Yes |
| Best suited for | Changeable ordered collection | Fixed ordered collection | Lookup by meaningful key |
Textbook Exercise – Solved
Question 1: Find the output
Given:
tuple1 = (23, 1, 45, 67, 45, 9, 55, 45)
tuple2 = (100, 200)
print(tuple1.index(45))2. The first occurrence of 45 is at index 2.print(tuple1.count(45))3. The value 45 occurs three times.print(tuple1 + tuple2)(23, 1, 45, 67, 45, 9, 55, 45, 100, 200).print(len(tuple2))2.print(max(tuple1))67.print(min(tuple1))1.print(sum(tuple2))300.print(sorted(tuple1)); print(tuple1)[1, 9, 23, 45, 45, 45, 55, 67]. Second output: (23, 1, 45, 67, 45, 9, 55, 45). Sorting returns a new list; the original tuple is unchanged.Question 2: Dictionary stateCapital
stateCapital = {
"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
print(stateCapital.get("Bihar"))Patnaprint(stateCapital.keys())dict_keys(['AndhraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan'])print(stateCapital.values())dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur'])print(stateCapital.items())dict_items([('AndhraPradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra', 'Mumbai'), ('Rajasthan', 'Jaipur')])print(len(stateCapital))4print("Maharashtra" in stateCapital)True, because Maharashtra is a key.print(stateCapital.get("Assam"))None, because Assam is not a key and no default was supplied.del stateCapital["Rajasthan"]
print(stateCapital)Output: {'AndhraPradesh': 'Hyderabad', 'Bihar': 'Patna', 'Maharashtra': 'Mumbai'}.Question 3: “Lists and Tuples are ordered”. Explain.
(10, 20, 30) has 10 at index 0 and 30 at index 2. A dictionary is accessed by keys rather than positional indexes.Question 4: Return more than one value from a function.
def calculate(a, b):
total = a + b
difference = a - b
return total, difference
s, d = calculate(20, 5)
print("Sum:", s)
print("Difference:", d)Sum: 25
Difference: 15
The return statement returns a tuple containing both values. Tuple unpacking assigns them to s and d.
Question 5: Advantages of tuples over lists
- Tuples are immutable, so their element positions cannot be accidentally reassigned.
- They communicate that the stored sequence is intended to remain fixed.
- They can be used as dictionary keys when all their elements are hashable.
- They are often suitable for fixed records and can be more memory-efficient than lists for comparable data.
Question 6: When to use tuple or dictionary?
(latitude, longitude), RGB colour (255, 100, 50), or a function returning several related values. Use a dictionary when data must be retrieved by a meaningful key, such as a student's roll number mapped to details, a product code mapped to price, or a state mapped to its capital.Question 7: Show that a variable is rebuilt for immutable data types.
x = 10
print(id(x))
x = x + 1
print(id(x))x + 1 creates/uses a new integer object and the variable x is bound to the resulting object. The exact numeric values returned by id() are implementation- and run-dependent, so compare the behaviour rather than memorising an address.Question 8: Why does the TypeError occur and how can it be corrected?
tuple1 = (5) # actually an integer
len(tuple1) # TypeErrortuple1 = (5,). Then len(tuple1) returns 1.Programming Problems – Model Solutions
1. Store email IDs, usernames and domains in tuples
n = int(input("How many email IDs? "))
emails = ()
for i in range(n):
email = input("Enter email ID: ").strip()
emails += (email,)
usernames = ()
domains = ()
for email in emails:
username, domain = email.split("@", 1)
usernames += (username,)
domains += (domain,)
print("Email IDs:", emails)
print("Usernames:", usernames)
print("Domains:", domains)Explanation: Each email is stored in a tuple. split("@", 1) separates the username from the domain at the first @ symbol. The corresponding parts are appended to new tuples through concatenation.
2. Search for a student name in a tuple
n = int(input("Number of students: "))
names = ()
for i in range(n):
names += (input("Enter student name: ").strip(),)
search_name = input("Name to search: ").strip()
if search_name in names:
print(search_name, "is present.")
else:
print(search_name, "is not present.")
3. Find the highest two values in a dictionary
Assumption: display the two highest distinct numeric values. If fewer than two distinct values exist, display the available values.
marks = {'Aman': 87, 'Geet': 95, 'Sahil': 91, 'Pawan': 95}
highest_values = sorted(set(marks.values()), reverse=True)[:2]
print("Highest values:", highest_values)Highest values: [95, 91]
4. Create a character-frequency dictionary from a string
text = "w3resource"
frequency = {}
for ch in text:
if ch in frequency:
frequency[ch] += 1
else:
frequency[ch] = 1
print(frequency){'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}
Dictionary display order follows the order in which keys were first inserted in modern Python. The expected textbook output lists the same counts in a different order; the key–value counts are what matter.
5. Friends phone directory – add, display, delete, modify, search and sort
friends = {}
n = int(input("How many friends? "))
for i in range(n):
name = input("Friend name: ").strip()
phone = input("Phone number: ").strip()
friends[name] = phone
# (a) Display all contacts
print("\\nAll friends:")
for name, phone in friends.items():
print(name, ":", phone)
# (b) Add a new friend
name = input("\\nNew friend name: ").strip()
phone = input("New phone number: ").strip()
friends[name] = phone
print("Updated dictionary:", friends)
# (c) Delete a friend
name = input("Name to delete: ").strip()
if name in friends:
del friends[name]
else:
print("Friend not found.")
# (d) Modify a phone number
name = input("Name whose number should change: ").strip()
if name in friends:
friends[name] = input("New phone number: ").strip()
else:
print("Friend not found.")
# (e) Search for a friend
name = input("Name to search: ").strip()
if name in friends:
print(name, ":", friends[name])
else:
print("Friend not found.")
# (f) Display contacts sorted by name
print("\\nContacts in sorted name order:")
for name in sorted(friends):
print(name, ":", friends[name])Case-study-based Questions and Suggested Design
A. SMIS – Student Management Information System
The textbook asks for a program that accepts roll number, name and percentage for n Class X students, then provides functions to accept records, search by roll number, display all results, find the class topper and find subject toppers. The hint recommends a dictionary whose key is roll number and whose value is an immutable tuple containing student name and percentage. For subject-wise topper analysis, the record must also contain subject marks.
# Example data model for the extended SMIS
students = {
101: ("Aman", 92.5, (90, 95, 92)),
102: ("Geet", 96.0, (98, 94, 96)),
103: ("Sahil", 88.0, (85, 90, 89))
}
subject_names = ("English", "Maths", "Computer Science")
def display_all(data):
for roll, record in data.items():
name, percentage, marks = record
print(roll, name, percentage, marks)
def search_student(data, roll):
if roll in data:
print("Student:", roll, data[roll])
else:
print("Roll number not found.")
def find_class_topper(data):
if not data:
print("No student records.")
return
roll, record = max(data.items(), key=lambda item: item[1][1])
print("Class topper:", roll, record)
def find_subject_toppers(data, subjects):
for index, subject in enumerate(subjects):
if not data:
continue
roll, record = max(data.items(), key=lambda item: item[1][2][index])
print(subject, "topper:", roll, record[0],
"Marks:", record[2][index])
Design note: The source hint specifies name and percentage in the tuple. Subject-wise topper calculation additionally requires subject marks, so the example extends the record structure to include a tuple of subject marks. The exact subject list and input format should be chosen for the school dataset.
B. Case study 1 – Bank account system
The textbook asks students to investigate a bank's account-opening form, savings interest rate and minimum balance, and then design a menu-driven program for account opening, deposits, withdrawals and fixed deposits. The minimum balance and interest rates must be obtained from the bank rather than invented.
- Suggested account record: account number as key; customer name, balance and account type as values.
- Deposit: accept a positive amount and add it to the balance.
- Withdrawal: permit only if the remaining balance is at least the bank's minimum balance.
- Fixed deposit: collect principal and period, then calculate maturity using the rate/slab actually researched.
- Use separate functions for opening account, deposit, withdraw and FD maturity.
accounts = {}
def open_account(account_no, name, opening_balance):
if account_no in accounts:
print("Account already exists.")
else:
accounts[account_no] = {
"name": name,
"balance": opening_balance
}
def deposit(account_no, amount):
if account_no in accounts and amount > 0:
accounts[account_no]["balance"] += amount
def withdraw(account_no, amount, minimum_balance):
if account_no not in accounts or amount <= 0:
return False
new_balance = accounts[account_no]["balance"] - amount
if new_balance >= minimum_balance:
accounts[account_no]["balance"] = new_balance
return True
return False
C. Case study 2 – Quiz system
The required features include an administrator ID/password to add, modify and delete questions; student registration; category selection; displaying questions by category; maintaining score; and showing the final score.
questions = {
"Python": [
{"question": "Which symbol starts a tuple?",
"options": ["[]", "()", "{}", "<>"],
"answer": "()"}
],
"Computer": [
{"question": "CPU stands for?",
"options": ["Central Processing Unit", "Computer Personal Unit"],
"answer": "Central Processing Unit"}
]
}
def play_quiz(category):
score = 0
for item in questions.get(category, []):
print(item["question"])
for option in item["options"]:
print("-", option)
answer = input("Your answer: ").strip()
if answer.lower() == item["answer"].lower():
score += 1
print("Final score:", score)
For a complete implementation, add authenticated admin functions for creating, editing and deleting question records, student registration, and input validation. Passwords should not be stored as plain text in a real application.
D. Case study 3 – Indian World Heritage Sites
Collect each site's name, district, state, year built, builder, purpose and website link (if any). The program should allow an administrator to add, modify and delete a site; display all sites; search by name; and list sites by state.
heritage = {
"Example Site": {
"district": "Example District",
"state": "Example State",
"year": "Research required",
"built_by": "Research required",
"purpose": "Research required",
"website": ""
}
}
def display_sites(data):
for name, details in data.items():
print(name, details)
def search_site(data, site_name):
return data.get(site_name, "Site not found")
def sites_by_state(data, state_name):
for name, details in data.items():
if details["state"].lower() == state_name.lower():
print(name)
Replace the placeholder record with verified information collected from reliable sources; this chapter's case study is an assignment prompt, not a supplied heritage-site dataset.
E. Case study 4 – Transport reservation system
The textbook illustrates a railway reservation system as connected subsystems: train information (days, timings, stations, classes and berths), reservation information (booking open/closed, available/waiting list, cancellation and refund), staff/security/infrastructure information, food service, billing service and other railway details. Students must select a transport mode and automate its reservation requirements using functions.
- Train/transport data: route, schedule, stations and class/capacity.
- Reservation data: booking status, passenger details, seat/berth allocation and waitlist.
- Cancellation/refund: update booking status and calculate refund according to defined rules.
- Billing: calculate fare and payment details.
- Other service data: food or passenger support where relevant.
Use dictionaries for records keyed by train/route/booking ID and tuples for fixed fields where appropriate. The figure on textbook page 228 presents these components as subsystems that work together.
Peer review activity
The chapter asks students to peer-review other groups' case studies using the documentation tips at the end of Chapter 5 and provide feedback. Review whether requirements, data structures, functions, test cases, outputs and documentation are clear and complete.
Quick Revision: Syntax and Common Mistakes
| Task | Correct syntax |
|---|---|
| Create tuple | t = (10, 20, 30) |
| One-element tuple | t = (10,) |
| Access tuple element | t[0] |
| Slice tuple | t[1:4] |
| Join tuples | t3 = t1 + t2 |
| Repeat tuple | t * 3 |
| Check tuple membership | x in t |
| Unpack tuple | a, b = (10, 20) |
| Create dictionary | d = {'A': 10, 'B': 20} |
| Read dictionary value | d['A'] |
| Safe lookup | d.get('A') |
| Add/update item | d['C'] = 30 |
| Traverse dictionary | for k, v in d.items(): |
| Delete item | del d['A'] |
| Empty dictionary | d.clear() |
Common student mistakes
- Writing
(5)instead of(5,)for a single-element tuple. - Trying to assign to a tuple index, for example
t[0] = 99. - Forgetting that the stop index in slicing is excluded.
- Assuming
sorted(t)returns a tuple; it returns a list. - Calling
index(x)when x may not be present. - Using a dictionary value as though it were a key in
x in d. - Using
d['missing']when a key may not exist; useget()or check membership. - Using a list as a dictionary key; mutable lists are not hashable.
- Using duplicate dictionary keys; later assignment overwrites the earlier value.
- Confusing
del d(delete variable) withd.clear()(empty dictionary).
for, if, get(), items() and update().TEXTBOOK SOLUTION
Step-by-step solved textbook exercises, derivations, and solutions.
Exercise Solutions Being Updated
Step-by-step verified exercise solutions are currently being uploaded.
IMPORTANT QUESTION
High-yield board questions, previous year questions (PYQs), and model answer keys.
Important Questions Being Compiled
Board blueprint and previous years' exam questions for this chapter will be live soon.