CHAPTER PDF
Complete curriculum textbook chapter document for reading and offline study.
NOTES
Complete conceptual breakdown, formulas, diagrams, and memory aids.
Chapter 4: Working with Lists and Dictionaries
Complete, student-friendly notes with definitions, syntax, worked examples, outputs, list and dictionary methods, programming applications, solved textbook exercises and case-study guidance.
Learning objectives
After studying this chapter, learners should be able to create and manipulate Python lists and dictionaries, access and traverse their elements, use built-in methods and functions, and develop programs that store and process related data.
Chapter flow: Lists are used to store ordered collections of values. Dictionaries store information as key–value pairs, making retrieval possible through meaningful keys.
4.1 Introduction to List
A list is an ordered sequence that is mutable and contains one or more elements. A list can store values of different data types, such as integers, floating-point numbers, strings, tuples and even other lists.
- List elements are enclosed in square brackets
[ ]. - Elements are separated by commas.
- A list can contain duplicate values.
- A list can contain mixed data types.
- A list is ordered, so the position of each element is maintained.
Syntax
list_name = [element1, element2, element3, ...]
Examples
# List of even numbers
list1 = [2, 4, 6, 8, 10, 12]
print(list1)
# List of vowels
list2 = ['a', 'e', 'i', 'o', 'u']
print(list2)
# List containing mixed data types
list3 = [100, 23.5, 'Hello']
print(list3)
# Nested list (a list containing other lists)
list4 = [['Physics', 101],
['Chemistry', 202],
['Mathematics', 303]]
print(list4)
[2, 4, 6, 8, 10, 12] ['a', 'e', 'i', 'o', 'u'] [100, 23.5, 'Hello'] [['Physics', 101], ['Chemistry', 202], ['Mathematics', 303]]
Empty list
empty_list = [] # Alternatively empty_list = list()
list4, each subject-and-code pair is itself a list.4.1.1 Accessing Elements in a List
Each element in a list is accessed using an index. Positive indexing starts from 0 at the left. Negative indexing accesses elements from the right, starting at -1.
| Element | Positive index | Negative index |
|---|---|---|
| First | 0 | -6 |
| Second | 1 | -5 |
| Third | 2 | -4 |
| Fourth | 3 | -3 |
| Fifth | 4 | -2 |
| Sixth | 5 | -1 |
Syntax
list_name[index]
Example
list1 = [2, 4, 6, 8, 10, 12] print(list1[0]) # First element print(list1[3]) # Fourth element print(list1[-1]) # Last element print(list1[-6]) # First element using negative index print(list1[1 + 4]) # Index expression evaluates to 5 print(len(list1)) # Number of elements
2 8 12 2 12 6
To retrieve the last element using the length:
n = len(list1) print(list1[n - 1]) # Last element print(list1[-n]) # First element
list1[15] raises IndexError: list index out of range.4.1.2 Lists are Mutable
Mutable means that the contents of an object can be changed after it has been created. A list allows an element to be replaced by assigning a new value at its index.
Syntax
list_name[index] = new_value
Example
colours = ['Red', 'Green', 'Blue', 'Orange'] colours[3] = 'Black' print(colours)
['Red', 'Green', 'Blue', 'Black']
The fourth element, 'Orange', is replaced with 'Black'. The list itself is modified.
4.2 List Operations
4.2.1 Concatenation (+)
Concatenation joins two or more lists. The + operator places the elements of the second list after the elements of the first list.
list1 = [1, 3, 5, 7, 9] list2 = [2, 4, 6, 8, 10] list3 = list1 + list2 print(list3) print(list1) # Original list remains unchanged
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10] [1, 3, 5, 7, 9]
[1, 2, 3] + "abc" raises a TypeError. Assign the result if you want to retain the concatenated list.4.2.2 Repetition (*)
The repetition operator repeats the contents of a list the specified number of times.
list1 = ['Hello'] print(list1 * 4)
['Hello', 'Hello', 'Hello', 'Hello']
4.2.3 Membership (in and not in)
in checks whether an element is present in a list. not in checks whether it is absent. Both return Boolean values: True or False.
colours = ['Red', 'Green', 'Blue']
print('Green' in colours)
print('Cyan' in colours)
print('Cyan' not in colours)
print('Green' not in colours)True False True False
4.2.4 Slicing
Slicing extracts a portion of a list and returns it as a new list. The stop index is excluded.
Syntax
list_name[start : stop : step]
| Part | Meaning |
|---|---|
start | Index from which extraction begins; default is the beginning. |
stop | Index at which extraction stops; this index is not included. |
step | Number of positions to move each time; default is 1. |
Slicing examples
items = ['Red', 'Green', 'Blue', 'Cyan',
'Magenta', 'Yellow', 'Black']
print(items[2:6])
print(items[2:20]) # Stops at the end of the list
print(items[7:2]) # Start is greater than stop
print(items[:5]) # From beginning to index 4
print(items[0:6:2]) # Every second element
print(items[-6:-2]) # Negative indexes
print(items[::2]) # Whole list, step 2
print(items[::-1]) # Reverse order
['Blue', 'Cyan', 'Magenta', 'Yellow'] ['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black'] [] ['Red', 'Green', 'Blue', 'Cyan', 'Magenta'] ['Red', 'Blue', 'Magenta'] ['Green', 'Blue', 'Cyan', 'Magenta'] ['Red', 'Blue', 'Magenta', 'Black'] ['Black', 'Yellow', 'Magenta', 'Cyan', 'Blue', 'Green', 'Red']
4.3 Traversing a List
Traversing means visiting or accessing each element of a list one by one. The chapter demonstrates traversal using a for loop directly and using range() with len().
Method 1: Direct traversal using for loop
colours = ['Red', 'Green', 'Blue', 'Yellow', 'Black']
for item in colours:
print(item)
Red Green Blue Yellow Black
Method 2: Traversal using range() and len()
colours = ['Red', 'Green', 'Blue', 'Yellow', 'Black']
for i in range(len(colours)):
print(colours[i])
Red Green Blue Yellow Black
len(list_name)returns the total number of elements.range(n)generates integers from 0 up to, but not including, n.- Use index-based traversal when the position of an element is also required.
4.4 List Methods and Built-in Functions
Python provides methods and built-in functions for creating, examining and modifying lists. Methods such as append() and sort() are called using dot notation on a list. Functions such as len(), sorted() and sum() are called by passing a list as an argument.
| Method / function | Purpose | Example and result |
|---|---|---|
len() | Returns number of elements. | len([10,20,30]) → 3 |
list() | Creates an empty list or converts a sequence into a list. | list('aeiou') → ['a','e','i','o','u'] |
append(x) | Adds one element at the end. A list passed to append is added as one nested element. | a=[10,20]; a.append([30,40]) → [10,20,[30,40]] |
extend(iterable) | Adds each element of the supplied iterable to the end. | a=[10,20]; a.extend([30,40]) → [10,20,30,40] |
insert(i,x) | Inserts x at index i. | a=[10,20,30]; a.insert(1,15) → [10,15,20,30] |
count(x) | Counts occurrences of x. | [10,20,10].count(10) → 2 |
index(x) | Returns index of first occurrence; raises ValueError if absent. | [10,20,30].index(20) → 1 |
remove(x) | Removes the first occurrence of value x; raises ValueError if absent. | a=[10,20,10]; a.remove(10) → [20,10] |
pop(i) | Returns and removes item at index i. Without an index, removes the last item. | a=[10,20,30]; a.pop() → returns 30; a becomes [10,20] |
reverse() | Reverses the list in place. | a=[1,2,3]; a.reverse() → [3,2,1] |
sort() | Sorts the same list in place; use reverse=True for descending order. | a=[3,1,2]; a.sort() → [1,2,3] |
sorted() | Returns a new sorted list; original list remains unchanged. | sorted([3,1,2]) → [1,2,3] |
min() | Returns smallest element. | min([34,12,63]) → 12 |
max() | Returns largest element. | max([34,12,63]) → 63 |
sum() | Returns sum of numeric elements. | sum([10,20,30]) → 60 |
Important examples
# append() adds one object a = [10, 20, 30, 40] a.append([50, 60]) print(a) # extend() adds the elements individually b = [10, 20, 30] b.extend([40, 50]) print(b) # sort() changes the original list marks = [34, 66, 12, 89, 28, 99] marks.sort(reverse=True) print(marks) # sorted() creates a separate sorted list numbers = [23, 45, 11, 67, 85, 56] new_numbers = sorted(numbers) print(numbers) print(new_numbers)
[10, 20, 30, 40, [50, 60]] [10, 20, 30, 40, 50] [99, 89, 66, 34, 28, 12] [23, 45, 11, 67, 85, 56] [11, 23, 45, 56, 67, 85]
find() for locating an element, but the Python list method used in the example is index(). Python's built-in list type uses index(), not find(). Use index() in executable Python code.4.5 List Manipulation
This section applies list methods to practical programs. The following corrected, runnable versions preserve the chapter's objectives and menu operations while using consistent Python syntax and safer input conversion.
Program 4-1: Menu-driven list operations
Allows the user to append, insert, extend, modify, delete by position, delete by value, sort ascending/descending and display a list.
myList = [22, 4, 16, 38, 13]
for attempt in range(3):
print("\\nCurrent list:", myList)
print("1. Append an element")
print("2. Insert an element")
print("3. Append another list")
print("4. Modify an element")
print("5. Delete by position")
print("6. Delete by value")
print("7. Sort ascending")
print("8. Sort descending")
print("9. Display list")
choice = int(input("Enter your choice (1-9): "))
if choice == 1:
value = int(input("Enter element: "))
myList.append(value)
elif choice == 2:
value = int(input("Enter element: "))
pos = int(input("Enter index: "))
myList.insert(pos, value)
elif choice == 3:
newList = list(map(int, input("Enter numbers separated by spaces: ").split()))
myList.extend(newList)
elif choice == 4:
pos = int(input("Enter index to modify: "))
if 0 <= pos < len(myList):
myList[pos] = int(input("Enter new value: "))
else:
print("Invalid position")
elif choice == 5:
pos = int(input("Enter index to delete: "))
if 0 <= pos < len(myList):
print("Deleted:", myList.pop(pos))
else:
print("Invalid position")
elif choice == 6:
value = int(input("Enter value to delete: "))
if value in myList:
myList.remove(value)
else:
print("Element not found")
elif choice == 7:
myList.sort()
elif choice == 8:
myList.sort(reverse=True)
elif choice == 9:
print("List:", myList)
else:
print("Invalid choice")
print("Final list:", myList)
Program 4-2: Average marks of n students
marks_list = []
n = int(input("How many students? "))
for i in range(n):
mark = int(input("Enter marks of student " + str(i + 1) + ": "))
marks_list.append(mark)
total = 0
for mark in marks_list:
total = total + mark
if n > 0:
average = total / n
print("Average marks:", average)
else:
print("No marks were entered.")
Sample output: For marks 45, 89, 79, 76 and 55, total is 344 and average is 68.8.
Program 4-3: Search for a number and display its position
numbers = []
n = int(input("How many numbers? "))
for i in range(n):
value = int(input("Enter number: "))
numbers.append(value)
search_num = int(input("Enter number to search: "))
position = -1
for i in range(len(numbers)):
if numbers[i] == search_num:
position = i
break
if position == -1:
print("Number is not present in the list")
else:
print("Number is present at position", position + 1)
position + 1 when reporting the position to a user.4.6 Introduction to Dictionaries
A dictionary is a mapping data type that stores information as key–value pairs. Each key maps to a value. A key and its value are separated by a colon (:), and pairs are separated by commas.
- A dictionary is written inside curly braces
{ }. - Each item has the form
key: value. - Keys must be unique.
- Keys must be immutable types, such as numbers, strings or tuples containing immutable elements.
- Values can be of different data types and may be repeated.
- Modern Python dictionaries preserve insertion order.
Syntax
dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}
Examples
# Empty dictionary
dict1 = {}
# Student names mapped to marks
student_marks = {
'Mohan': 95,
'Ram': 89,
'Suhel': 92,
'Sangeeta': 85
}
print(student_marks)
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
'Ram': 89, 'Ram' is the key and 89 is the value. The key is used to retrieve the associated value.4.6.1 Creating and Accessing Dictionary Items
Dictionary values are accessed by using their keys, not by using numerical positions.
Syntax
dictionary_name[key]
Example
student_marks = {
'Mohan': 95,
'Ram': 89,
'Suhel': 92,
'Sangeeta': 85
}
print(student_marks['Ram'])
print(student_marks['Sangeeta'])
89 85
KeyError. For example, student_marks['Shyam'] raises KeyError: 'Shyam'. The get() method can be used when a missing key should not raise an error.4.6.2 Membership Operation and Dictionary Mutability
Membership: in and not in
For dictionaries, membership operators check for the presence of a key, not a value.
student_marks = {'Mohan': 95, 'Ram': 89, 'Suhel': 92}
print('Suhel' in student_marks)
print('Suhel' not in student_marks)
print(92 in student_marks)
True False False
Dictionaries are mutable
Dictionary contents can be changed after creation.
(A) Adding a new item
student_marks = {'Mohan': 95, 'Ram': 89, 'Suhel': 92}
student_marks['Meena'] = 78
print(student_marks)
(B) Modifying an existing item
student_marks['Suhel'] = 93.5 print(student_marks)
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Meena': 78}
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Meena': 78}
Assigning a value to an existing key replaces its old value. Assigning a value to a new key creates a new key–value pair.
4.7 Traversing a Dictionary
A for loop can visit dictionary entries. The chapter shows two approaches.
Method 1: Traverse keys and access values
student_marks = {
'Mohan': 95,
'Ram': 89,
'Suhel': 92,
'Sangeeta': 85
}
for key in student_marks:
print(key, ':', student_marks[key])
Method 2: Use items() to get key and value together
for key, value in student_marks.items():
print(key, ':', value)
Mohan : 95 Ram : 89 Suhel : 92 Sangeeta : 85
The second method uses tuple unpacking: each pair returned by items() is assigned to key and value.
4.8 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 an empty dictionary or converts key–value pairs into a dictionary. | dict([('A',1),('B',2)]) → {'A':1,'B':2} |
keys() | Returns a view containing all keys. | d.keys() |
values() | Returns a view containing all values. | d.values() |
items() | Returns a view of (key, value) pairs. | d.items() |
get(key) | Returns the value for key; returns None if absent unless a default is supplied. | d.get('A') |
update(other) | Adds pairs from another mapping; matching keys are overwritten. | d.update({'C':3}) |
clear() | Removes all items from the dictionary. | d.clear() |
del d[key] | Deletes the item with the specified key. | del d['A'] |
Worked examples
student_marks = {
'Mohan': 95, 'Ram': 89,
'Suhel': 92, 'Sangeeta': 85
}
print(len(student_marks))
print(student_marks.keys())
print(student_marks.values())
print(student_marks.items())
print(student_marks.get('Sangeeta'))
print(student_marks.get('Sohan'))
4
dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta'])
dict_values([95, 89, 92, 85])
dict_items([('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)])
85
None
update(), clear() and del
d1 = {'Mohan': 95, 'Ram': 89}
d2 = {'Sohan': 79, 'Geeta': 89}
d1.update(d2)
print(d1)
d1.clear()
print(d1)
d3 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92}
del d3['Ram']
print(d3)
# Delete the entire dictionary name
del d3
{'Mohan': 95, 'Ram': 89, 'Sohan': 79, 'Geeta': 89}
{}
{'Mohan': 95, 'Suhel': 92}
clear() empties a dictionary but the variable remains. del d removes the variable binding itself; trying to use that name afterwards causes NameError.4.9 Manipulating Dictionaries
Example: Dictionary of odd numbers
ODD = {
1: 'One',
3: 'Three',
5: 'Five',
7: 'Seven',
9: 'Nine'
}
print(ODD)
print(ODD.keys())
print(ODD.values())
print(ODD.items())
print(len(ODD))
print(7 in ODD)
print(2 in ODD)
print(ODD.get(9))
del ODD[9]
print(ODD)
Program 4-4: Store employee names and salaries
n = int(input("Enter number of employees: "))
employee = {}
for i in range(n):
name = input("Enter employee name: ")
salary = int(input("Enter salary: "))
employee[name] = salary
print("\\nEMPLOYEE NAME\\tSALARY")
for name, salary in employee.items():
print(name, "\\t\\t", salary)
The employee name is used as the key and salary as its value. Each new entry is stored using employee[name] = salary.
Program 4-5: Count the 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
Each character becomes a dictionary key. Its value stores the number of times it has appeared. The program is case-sensitive, so H and h are different keys.
Program 4-6: Convert digits of a number into words
num = input("Enter any number: ")
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
print("The number is:", num)
print("The number name is:", result.strip())
Enter any number: 6512 The number is: 6512 The number name is: Six Five One Two
The input is read as a string so that each digit can be processed separately. Each digit is converted to an integer and used as a dictionary key.
Chapter Summary
- A list is an ordered, mutable sequence. Its elements are enclosed in square brackets and separated by commas.
- List indexing starts at 0. Negative indexes access elements from the right.
- Lists can be modified after creation.
+concatenates lists;*repeats list contents.inandnot intest membership.- Slicing extracts a portion of a list.
- Lists can be traversed using
forloops. - Important list methods/functions include
len(),list(),append(),extend(),insert(),count(),index(),remove(),pop(),reverse(),sort(),sorted(),min(),max()andsum(). - A dictionary stores data as key–value pairs inside curly braces.
- Dictionary keys are unique and immutable; values may be repeated and may be of different data types.
- Dictionary values are accessed using keys.
- Dictionaries are mutable and can be traversed using a
forloop. - Important dictionary methods include
keys(),values(),items(),get(),update()andclear().
Quick comparison: List vs Dictionary
| Basis | List | Dictionary |
|---|---|---|
| Structure | Sequence of elements | Key–value pairs |
| Brackets | [ ] | { } |
| Access | By index | By key |
| Order | Ordered | Insertion order preserved in modern Python |
| Mutability | Mutable | Mutable |
| Duplicate data | Duplicate elements allowed | Keys must be unique; values may repeat |
| Example | [10, 20, 30] | {'A': 10, 'B': 20} |
Textbook Exercise – Solved Answers
The following answers correspond to the end-of-chapter exercise on printed pages 75–76 of the supplied PDF.
1. Predict the output
(a)
list1 = [12, 32, 65, 26, 80, 10] list1.sort() print(list1)
[10, 12, 26, 32, 65, 80]
(b)
list1 = [12, 32, 65, 26, 80, 10] sorted(list1) print(list1)
[12, 32, 65, 26, 80, 10]
sorted() returns a new list; the returned list is not assigned, so list1 remains unchanged.
(c)
list1 = [1,2,3,4,5,6,7,8,9,10] print(list1[::-2]) print(list1[:3] + list1[3:])
[10, 8, 6, 4, 2] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(d)
list1 = [1,2,3,4,5] print(list1[len(list1)-1])
5
2. List after operations
myList = [10, 20, 30, 40] myList.append([50, 60]) print(myList)
[10, 20, 30, 40, [50, 60]]
After part (a), if part (b) is performed on the resulting list:
myList.extend([80, 90]) print(myList)
[10, 20, 30, 40, [50, 60], 80, 90]
3. Output of the even-index loop
myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0, len(myList)):
if i % 2 == 0:
print(myList[i])1 3 5 7 9
4. Output of del with slices
(a) Delete from index 3 to the end:
myList = [1,2,3,4,5,6,7,8,9,10] del myList[3:] print(myList)
[1, 2, 3]
(b) Delete the first five elements:
myList = [1,2,3,4,5,6,7,8,9,10] del myList[:5] print(myList)
[6, 7, 8, 9, 10]
(c) Delete elements at indexes 0, 2, 4, 6 and 8:
myList = [1,2,3,4,5,6,7,8,9,10] del myList[::2] print(myList)
[2, 4, 6, 8, 10]
5. Differentiate append() and extend()
| append() | extend() |
|---|---|
| Adds its argument as one element at the end. | Adds each element from the iterable separately. |
a=[1,2]; a.append([3,4]) → [1,2,[3,4]] | a=[1,2]; a.extend([3,4]) → [1,2,3,4] |
6. Difference between list1 * 2, list1 *= 2 and list1 = list1 * 2
For list1 = [6,7,8,9]:
list1 * 2creates and returns a repeated list but does not changelist1unless assigned.list1 *= 2performs in-place repetition and updates the list.list1 = list1 * 2creates a repeated list and assigns it to the variable namelist1.
All three produce the repeated value [6,7,8,9,6,7,8,9] as an expression/result; only the first leaves the original variable unchanged.
7. Retrieve information from stRecord
stRecord = ['Raman', 'A-36', [56, 98, 99, 72, 69], 78.8] # (a) Percentage print(stRecord[3]) # (b) Marks in fifth subject print(stRecord[2][4]) # (c) Maximum marks print(max(stRecord[2])) # (d) Roll number print(stRecord[1]) # (e) Change name stRecord[0] = 'Raghav' print(stRecord)
78.8 69 99 A-36 ['Raghav', 'A-36', [56, 98, 99, 72, 69], 78.8]
8. Dictionary stateCapital – outputs
stateCapital = {
"Assam": "Guwahati",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"
}
print(stateCapital.get("Bihar"))
print(stateCapital.keys())
print(stateCapital.values())
print(stateCapital.items())
print(len(stateCapital))
print("Maharashtra" in stateCapital)
print(stateCapital.get("Assam"))
del stateCapital["Assam"]
print(stateCapital)Patna
dict_keys(['Assam', 'Bihar', 'Maharashtra', 'Rajasthan'])
dict_values(['Guwahati', 'Patna', 'Mumbai', 'Jaipur'])
dict_items([('Assam', 'Guwahati'), ('Bihar', 'Patna'), ('Maharashtra', 'Mumbai'), ('Rajasthan', 'Jaipur')])
4
True
Guwahati
{'Bihar': 'Patna', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur'}
Programming Problems – Suggested Solutions
These are complete sample solutions to the programming problems listed on printed pages 76–77. They are written as beginner-friendly implementations.
1. Count how many times an element occurs in a list
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))
target = int(input("Enter element to count: "))
print("Occurrences:", numbers.count(target))
2. Separate positive and negative numbers
numbers = list(map(int, input("Enter integers: ").split()))
positive = []
negative = []
for value in numbers:
if value > 0:
positive.append(value)
elif value < 0:
negative.append(value)
print("Original list:", numbers)
print("Positive numbers:", positive)
print("Negative numbers:", negative)
Zero is not placed in either list because it is neither positive nor negative.
3. Find largest and second largest distinct elements
numbers = list(map(int, input("Enter numbers: ").split()))
unique_numbers = sorted(set(numbers), reverse=True)
if len(unique_numbers) >= 2:
print("Largest:", unique_numbers[0])
print("Second largest:", unique_numbers[1])
else:
print("At least two distinct values are required.")
4. Find the median of a list
numbers = list(map(int, input("Enter numbers: ").split()))
numbers.sort()
n = len(numbers)
if n == 0:
print("Median is undefined for an empty list.")
elif n % 2 == 1:
print("Median:", numbers[n // 2])
else:
middle1 = numbers[n // 2 - 1]
middle2 = numbers[n // 2]
print("Median:", (middle1 + middle2) / 2)
5. Remove duplicate elements while preserving order
items = input("Enter items separated by spaces: ").split()
unique_items = []
for item in items:
if item not in unique_items:
unique_items.append(item)
print("List without duplicates:", unique_items)
6. Insert an element at a specified position
numbers = list(map(int, input("Enter numbers: ").split()))
value = int(input("Enter value to insert: "))
position = int(input("Enter index: "))
if 0 <= position <= len(numbers):
numbers.insert(position, value)
print(numbers)
else:
print("Invalid position")
7. Delete an element by position or by value
numbers = list(map(int, input("Enter numbers: ").split()))
# (a) Delete by index
position = int(input("Enter index to delete: "))
if 0 <= position < len(numbers):
removed = numbers.pop(position)
print("Removed:", removed)
else:
print("Invalid index")
# (b) Delete first matching value
value = int(input("Enter value to delete: "))
if value in numbers:
numbers.remove(value)
else:
print("Value not found")
print("Updated list:", numbers)
8. Find the two highest values in a dictionary
marks = {'Asha': 87, 'Ravi': 95, 'Neha': 91, 'Kabir': 78}
highest_two = sorted(marks.items(),
key=lambda item: item[1],
reverse=True)[:2]
for name, value in highest_two:
print(name, value)
9. Create a dictionary of each character and its first index in “w3resource”
text = 'w3resource'
char_index = {}
for index, char in enumerate(text):
if char not in char_index:
char_index[char] = index
print(char_index)
The dictionary stores the first occurrence index of each distinct character. The expected output in the textbook is shown in a different display order; dictionary order follows the order in which keys are first inserted in current Python.
10. Friend phone directory
friends = {}
n = int(input("How many friends? "))
for i in range(n):
name = input("Enter friend name: ")
phone = input("Enter phone number: ")
friends[name] = phone
# (a) Display all friends
for name, phone in friends.items():
print(name, ":", phone)
# (b) Add a friend
name = input("New friend's name: ")
phone = input("New friend's phone: ")
friends[name] = phone
# (c) Delete a friend
name = input("Name to delete: ")
if name in friends:
del friends[name]
# (d) Modify phone number
name = input("Name to update: ")
if name in friends:
friends[name] = input("New phone number: ")
# (e) Check whether a friend exists
name = input("Name to search: ")
print(name in friends)
# (f) Display sorted by name
for name in sorted(friends):
print(name, ":", friends[name])
Case Study-Based Questions
1. SMIS – Student records using a dictionary
The textbook asks for a program that accepts roll number, name and percentage for n students; searches by roll number; displays all records; finds the overall topper; and identifies subject toppers. The supplied chapter suggests a dictionary where roll number is the key and a tuple containing student details is the value.
Basic structure for student records
students = {}
n = int(input("Enter number of students: "))
for i in range(n):
roll = input("Enter roll number: ")
name = input("Enter name: ")
percentage = float(input("Enter percentage: "))
students[roll] = (name, percentage)
# Search by roll number
search_roll = input("Enter roll number to search: ")
if search_roll in students:
print("Student:", students[search_roll])
else:
print("Student not found")
# Display all records
for roll, details in students.items():
print(roll, details)
# Find overall topper
if students:
topper_roll = max(students, key=lambda r: students[r][1])
print("Topper:", topper_roll, students[topper_roll])
2. Banking application – deposit and withdrawal
The case study asks learners to investigate savings-account information, minimum balance and interest rates, then create a menu-driven program for account opening, deposits, withdrawals and fixed deposits. A basic deposit/withdrawal model is shown below. The balance and minimum balance are illustrative inputs, not real bank terms.
balance = float(input("Enter opening balance: "))
minimum_balance = float(input("Enter required minimum balance: "))
while True:
print("\\n1. Deposit")
print("2. Withdraw")
print("3. Display balance")
print("4. Exit")
choice = input("Enter choice: ")
if choice == '1':
amount = float(input("Deposit amount: "))
if amount > 0:
balance += amount
else:
print("Enter a positive amount")
elif choice == '2':
amount = float(input("Withdrawal amount: "))
if amount > 0 and balance - amount >= minimum_balance:
balance -= amount
else:
print("Withdrawal not permitted")
elif choice == '3':
print("Current balance:", balance)
elif choice == '4':
break
else:
print("Invalid choice")
3. Quiz application
The textbook asks for an administrative ID/password to manage questions, student registration, category selection, question display, score tracking and final score. A full application can store questions by category using a nested dictionary or list.
quiz = {
'Python': [
('Which symbol starts a list?', ['()', '{}', '[]', '<>'], 'C'),
('Which keyword starts a loop?', ['if', 'for', 'def', 'class'], 'B')
]
}
score = 0
name = input("Enter student name: ")
category = input("Choose category (Python): ")
if category in quiz:
for question, options, answer in quiz[category]:
print("\\n", question)
for label, option in zip(['A', 'B', 'C', 'D'], options):
print(label + '.', option)
response = input("Your answer: ").upper()
if response == answer:
score += 1
print("Student:", name)
print("Final score:", score, "out of", len(quiz[category]))
This is a learning prototype for the quiz-taking portion. The administrative authentication and add/modify/delete workflow can be added as separate functions.
4. Indian heritage sites directory
The textbook asks learners to collect each site's name, district, state, year built, builder, purpose and website link. The program should allow an administrator to add, modify or delete a site, display all sites, search by name and filter by state.
sites = {
'Example Monument': {
'district': 'Example District',
'state': 'Example State',
'built': 'Example year',
'builder': 'Example builder',
'purpose': 'Example purpose',
'website': 'Not provided'
}
}
# Display all site records
for name, details in sites.items():
print(name, details)
# Search by site name
search_name = input("Enter site name: ")
if search_name in sites:
print(sites[search_name])
else:
print("Site not found")
# Search by state
state = input("Enter state: ")
for name, details in sites.items():
if details['state'].lower() == state.lower():
print(name)
The sample record uses placeholder values; learners should research and enter verified heritage-site information rather than treating the placeholder as factual data.
Common mistakes to avoid
- Using an index that does not exist in a list.
- Confusing
append()withextend(). - Assuming
sort()andsorted()both modify the original list. - Forgetting that the stop index in a slice is excluded.
- Using a dictionary value to test membership when
inchecks keys. - Trying to create duplicate dictionary keys; a later assignment replaces the earlier value for that key.
- Using a mutable object such as a list as a dictionary key.
- Using square-bracket key access when a key may be absent without checking or using
get().
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.
MCQ
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.