Courses / Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course
3.3 Advanced Data Structures in Python: Lists, Nested Lists and Dictionaries
Unit 3 – Programming Fundamentals · 90 min read · 9 MCQs to check yourself
Nested lists and dictionaries in Python
1. Lists – ordered collections
The purpose of a list is to store an ordered sequence of elements that can change.
fruits = ["apple", "mango"]
fruits.append("banana") # add at end
fruits.insert(0, "kiwi") # add at position 0
fruits.extend(["grapes", "peach"])
fruits.remove("mango") # remove by value
last = fruits.pop() # remove and return the last item
del fruits[0] # remove by index
print(fruits, "| popped:", last)
print("apple" in fruits, len(fruits), sorted(fruits))
squares = [n * n for n in range(1, 6)] # list comprehension
print(squares, squares[1:4], squares[::-1])
Output:
['apple', 'banana', 'grapes'] | popped: peach
True 3 ['apple', 'banana', 'grapes']
[1, 4, 9, 16, 25] [4, 9, 16] [25, 16, 9, 4, 1]
2. Nested lists – a list within a list
A nested list stores a table: each inner list is a row.
marks = [
["Ali", 78, 85, 90],
["Sara", 91, 88, 95],
["Bilal", 66, 72, 58],
]
print(marks[1][0], marks[1][3]) # row 1, columns 0 and 3
for row in marks:
name, scores = row[0], row[1:]
print(f"{name:6} total={sum(scores)} average={sum(scores)/len(scores):.1f}")
marks[2].append(80) # add a mark to Bilal's row
print(marks[2])
Output:
Sara 95
Ali total=253 average=84.3
Sara total=274 average=91.3
Bilal total=196 average=65.3
['Bilal', 66, 72, 58, 80]
3. Dictionaries – key → value pairs
The purpose of a dictionary is to store key-value pairs. Keys are unique and immutable (numbers, strings, tuples).
student = {"name": "Sana", "roll": 103, "city": "Lahore"}
print(student["name"], student.get("phone", "not given"))
student["grade"] = 78 # add a new pair
student["city"] = "Islamabad" # update a value
del student["roll"] # remove a pair
print(student)
for key, value in student.items():
print(key, "->", value)
Output:
Sana not given
{'name': 'Sana', 'city': 'Islamabad', 'grade': 78}
name -> Sana
city -> Islamabad
grade -> 78
4. A list as a value within a dictionary
courses = {
"Ali": ["CS", "Physics", "Maths"],
"Sara": ["CS", "Biology"],
}
courses["Sara"].append("Chemistry") # add to Sara's list
courses["Bilal"] = ["Economics"] # new key with a list
for name, subjects in courses.items():
print(name, len(subjects), subjects)
print("Students taking CS:", [n for n, s in courses.items() if "CS" in s])
Output:
Ali 3 ['CS', 'Physics', 'Maths']
Sara 3 ['CS', 'Biology', 'Chemistry']
Bilal 1 ['Economics']
Students taking CS: ['Ali', 'Sara']
5. Why is finding by key faster in a dictionary?
A dictionary uses a hash table: Python turns the key into a number (hash) that points almost directly to where the value is stored, so lookup takes about the same time no matter how big the dictionary is (O(1) on average). Finding a value in a list means checking items one by one (O(n)).
import time
n = 1_000_000
id_list = list(range(n))
id_dict = {i: True for i in range(n)}
t = time.perf_counter(); found = (n - 1) in id_list; t_list = time.perf_counter() - t
t = time.perf_counter(); found = (n - 1) in id_dict; t_dict = time.perf_counter() - t
print("dictionary lookup is faster:", t_dict < t_list)
Output:
dictionary lookup is faster: True
6. Nested list vs dictionary (model-paper question)
Nested list [[101, "Ali", 85], …] |
Dictionary {101: {"name": "Ali", "grade": 85}, …} |
|
|---|---|---|
| Storage | Rows by position; columns by index | Records by key (Student ID); fields by name |
| Retrieval | Loop to find ID 102 – O(n); row[2] is unclear |
students[102]["grade"] – direct, O(1); self-describing |
| Order | Keeps order; easy to sort and print as a table | Keeps insertion order (Python 3.7+) |
| Best for | Small tables, matrices, data processed in order | Fast lookup by a unique ID, readable field names |
Short and long questions
1. Write a Python program that stores each student’s subjects as a list inside a dictionary. It should (a) add a new student, (b) add a subject for an existing student, (c) remove a subject, (d) print each student with the number of subjects, and (e) list students taking "CS". Explain why a dictionary is used. (5 + 1)
Model answer
courses = {"Ali": ["CS", "Physics"], "Sara": ["Biology", "CS"]}
courses["Bilal"] = ["Economics"] # (a) new student
courses["Ali"].append("Maths") # (b) add subject
courses["Sara"].remove("Biology") # (c) remove subject
for name, subjects in courses.items(): # (d)
print(name, len(subjects), subjects)
cs = [name for name, subjects in courses.items() if "CS" in subjects]
print("CS students:", cs) # (e) ['Ali', 'Sara']
Why a dictionary (1): each student name is a unique key that gives direct (O(1)) access to that student’s list of subjects; the list as a value can grow or shrink, and the code is easy to read.
2. Construct a dictionary of three products and prices, then retrieve one price, update one price and display all items.
Model answer
prices = {"pen": 50, "notebook": 200, "bag": 1500}
print(prices["notebook"]) # 200
prices["pen"] = 60 # update
for item, price in prices.items():
print(item, price)
3. What is a nested list? Write code to print the total marks of each student from a nested list.
Model answer
A nested list is a list whose elements are lists – useful for tables (rows and columns).
marks = [["Ali", 78, 85], ["Sara", 91, 88]]
for row in marks:
print(row[0], sum(row[1:])) # Ali 163, Sara 179
4. Write Python code to create a list of five cities, add one city, remove one city and print the list in sorted order.
Model answer
cities = ["Lahore", "Karachi", "Quetta", "Peshawar", "Multan"]
cities.append("Islamabad")
cities.remove("Quetta")
print(sorted(cities))
# ['Islamabad', 'Karachi', 'Lahore', 'Multan', 'Peshawar']
5. Here is sample data: Student ID 101 Ali 85; 102 Babar 90; 103 Sana 78. Use this data to compare storage and retrieval using a nested list and a dictionary in Python. (1.5 + 1.5)
Model answer
Nested list: records = [[101, "Ali", 85], [102, "Babar", 90], [103, "Sana", 78]] – stored by position. To get Babar’s grade you must loop to find ID 102 (O(n)); records[1][2] works but is unclear.
Dictionary: students = {101: {"name": "Ali", "grade": 85}, 102: {"name": "Babar", "grade": 90}, 103: {"name": "Sana", "grade": 78}} – stored by key. students[102]["grade"] retrieves 90 directly (O(1)) and field names make it readable. Dictionary is better for lookup by ID; a nested list is fine for printing a table in order.
This lesson ends with a quiz of 9 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: 3.2 Object-Oriented Programming in Python: Classes, Objects and State · Next: 3.4 File Handling in Python: Writing, Reading and Counting Letters
All lessons in Computer Science XII (HSSC-II) – FBISE Complete SLO-Based Course