Working with Lists and Dictionaries
Overview
This chapter introduces two of Python's most useful data structures. A list is an ordered, mutable sequence accessed by index, and students learn to create, slice, traverse and change lists with the methods in the syllabus. A dictionary stores key-value pairs accessed by key, and students learn to create, update, delete and traverse dictionaries and apply both structures to practical problems.
Fully in the 2025-26 syllabus. Named list methods and functions: len(), list(), append(), insert(), count(), index(), remove(), pop(), reverse(), sort(), min(), max(), sum(). Named dictionary operations: dict(), len(), keys(), values(), items(), update(), del, clear(). NCERT also shows extend(), sorted() and get(), which are marked as enrichment here.
Learning outcomes
- Students will be able to create and initialise lists and access items using positive and negative indexes.
- Students will be able to apply concatenation, repetition, membership and slicing to lists.
- Students will be able to traverse lists using for and while loops.
- Students will be able to use the list methods and functions len(), list(), append(), insert(), count(), index(), remove(), pop(), reverse(), sort(), min(), max() and sum().
- Students will be able to explain key-value pairs and create dictionaries using {} and dict().
- Students will be able to add, update, delete and traverse dictionary items using update(), del, clear(), keys(), values() and items().
- Students will be able to choose between a list and a dictionary and write programs that use them to solve everyday problems.
Lesson plan
Write a class's first five roll-call names on the board as a list and label positive and negative indexes. In the lab, students create lists of marks and cities and access items, deliberately triggering an IndexError.
Demonstrate aliasing with two name-boxes and one list. Students predict and check 10 slices of a days-of-the-week list, including [::-1].
Lab: total, average, highest and lowest marks of a list, first with loops and then with sum(), max(), min(), len(). Discuss when each loop form is needed.
Card activity: each group gets a method card (append, insert, count, index, remove, pop, reverse, sort) and demonstrates it on a 'list' of students standing in a line. Then fill the method summary table in notebooks.
Build the menu-driven list program together. Students write linear search and third-largest programs for the practical file.
Discuss real key-value data (PIN codes, roll numbers). Students create dictionaries in all the ways shown, and test duplicate keys and a list as a key.
Lab: a canteen price list dictionary; add, modify, update(), del, clear(); print the menu with items(). Compare del d and clear().
Frequency counting of letters and words; state-capital and student-marks dictionaries for the practical file; highest and lowest value in a dictionary.
Output-prediction worksheet on list and dictionary methods, an error-finding exercise, and a short lab test (one list program and one dictionary program).
Notes
Introduction to lists
A list is an ordered sequence of items written inside square brackets [ ] and separated by commas. Unlike variables that hold one value, a list stores many values under one name, for example the marks of a class or the names of players in a team.
Features of a list:
- Items keep their order and each item has a position (index).
- Items can be of different data types (int, float, string, even another list).
- Duplicate values are allowed.
- A list is mutable: items can be added, changed or removed after it is created.
Ways to create a list:
- Empty list:
[]orlist() - With values:
marks = [78, 85, 92] - From another sequence:
list("IP")gives['I', 'P'] - A list inside a list is a nested list:
[["Aman", 81], ["Riya", 94]]
marks = [78, 85, 92, 66]
student = ["Kavya", 16, 88.5, True] # mixed types
empty1 = []
empty2 = list()
letters = list("PYTHON")
nested = [["Aman", 81], ["Riya", 94]]
print(marks)
print(student)
print(empty1, empty2)
print(letters)
print(nested, len(nested))[78, 85, 92, 66] ['Kavya', 16, 88.5, True] [] [] ['P', 'Y', 'T', 'H', 'O', 'N'] [['Aman', 81], ['Riya', 94]] 2
Contrast with strings: a string is also an ordered sequence, but it holds only characters and is immutable. A list can hold anything and is mutable.
Accessing elements: indexing
Each item in a list has an index. Indexing works the same way as for strings:
- Positive (forward) index starts at
0for the first item and goes up tolen(list) - 1. - Negative (backward) index starts at
-1for the last item and goes down to-len(list).
The item is accessed as listname[index]. Using an index outside the valid range raises IndexError: list index out of range. For a nested list, use two indexes: nested[1][0] means "item 0 of item 1".
| Item | "Mumbai" | "Delhi" | "Chennai" | "Kolkata" | "Pune" |
|---|---|---|---|---|---|
| Positive index | 0 | 1 | 2 | 3 | 4 |
| Negative index | -5 | -4 | -3 | -2 | -1 |
cities = ["Mumbai", "Delhi", "Chennai", "Kolkata", "Pune"]
print(cities[0], cities[3], cities[-1], cities[-5])
print(cities[len(cities) - 1])
nested = [["Aman", 81], ["Riya", 94]]
print(nested[1][0], nested[1][1])
print(cities[5])Mumbai Kolkata Pune Mumbai Pune Riya 94 IndexError: list index out of range
For any list L, L[-1] is the same as L[len(L) - 1]. Negative indexes save students from calculating the length.
Lists are mutable
Because a list is mutable, an item can be changed in place by assigning to its index: scores[2] = 95. The list object stays the same; only its contents change. (Doing the same with a string gives a TypeError.)
Aliasing: writing list2 = list1 does not copy the list. Both names now refer to the same list, so a change made through one name is seen through the other.
To get an independent copy, use list2 = list(list1) or list2 = list1[:] (a full slice).
scores = [45, 67, 89, 72]
scores[2] = 95
print(scores)
team_a = ["Rohit", "Gill", "Kohli"]
team_b = team_a # alias, not a copy
team_b[0] = "Jaiswal"
print(team_a) # also changed!
team_c = list(team_a) # independent copy
team_c[1] = "Pant"
print(team_a, team_c)[45, 67, 95, 72] ['Jaiswal', 'Gill', 'Kohli'] ['Jaiswal', 'Gill', 'Kohli'] ['Jaiswal', 'Pant', 'Kohli']
Draw two name-boxes pointing to one list on the board to explain aliasing. Then draw the copy as a separate list. This prevents many surprises in practical work.
List operations: concatenation, repetition and membership
- Concatenation
+joins two lists into a new list:[1, 2] + [3]gives[1, 2, 3]. Both operands must be lists;[1, 2] + 3gives aTypeError. - Repetition
*repeats a list a given number of times:[0] * 4gives[0, 0, 0, 0]. Handy for creating a list of a fixed size. - Membership
in/not inchecks whether a value is an item of the list and returnsTrueorFalse.
The original lists are not changed by + and *; a new list is created.
morning = ["Maths", "IP"]
afternoon = ["English", "Physics"]
print(morning + afternoon)
print(["-"] * 5, [0] * 3)
print("IP" in morning, "Hindi" not in morning)
print(morning)
print(morning + "Biology")['Maths', 'IP', 'English', 'Physics'] ['-', '-', '-', '-', '-'] [0, 0, 0] True True ['Maths', 'IP'] TypeError: can only concatenate list (not "str") to list
To add a single item using +, it must be wrapped in a list: morning + ["Biology"]. Better still, use append().
Slicing a list
Slicing extracts a part of a list as a new list: L[start:stop:step].
- Items from index
startup tostop - 1are taken;stopis excluded. - If
startis omitted it is 0; ifstopis omitted it is the length;stepdefaults to 1. - Negative indexes and negative steps are allowed.
L[::-1]gives the list in reverse. - Slicing never raises
IndexError; indexes beyond the ends are simply trimmed.
A slice can also appear on the left of = to replace several items at once.
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
print(days[1:4])
print(days[:3], days[5:])
print(days[::2])
print(days[-3:-1])
print(days[::-1])
print(days[4:100])
nums = [10, 20, 30, 40, 50]
nums[1:3] = [21, 31]
print(nums)['Tue', 'Wed', 'Thu'] ['Mon', 'Tue', 'Wed'] ['Sat', 'Sun'] ['Mon', 'Wed', 'Fri', 'Sun'] ['Fri', 'Sat'] ['Sun', 'Sat', 'Fri', 'Thu', 'Wed', 'Tue', 'Mon'] ['Fri', 'Sat', 'Sun'] [10, 21, 31, 40, 50]
Ask students to always count how many items a slice gives: for a positive step 1, it is stop - start (when both are within range).
Traversing a list
Traversing means visiting every item of a list once, usually to process it (print, add, count or search). Three common ways:
for item in L:gives each value directly. Simplest when the position is not needed.for i in range(len(L)):gives each index; useL[i]for the value. Needed when items must be changed or positions printed.- A
whileloop with an index variable running from0tolen(L) - 1.
runs = [34, 78, 12, 101, 56]
for r in runs:
print(r, end=" ")
print()
for i in range(len(runs)):
print("Match", i + 1, ":", runs[i])
i = 0
total = 0
while i < len(runs):
total += runs[i]
i += 1
print("Total runs:", total)34 78 12 101 56 Match 1 : 34 Match 2 : 78 Match 3 : 12 Match 4 : 101 Match 5 : 56 Total runs: 281
If a program must modify items (for example add 5 grace marks to each), the first form does not work because r is only a copy of the value. Use for i in range(len(L)): L[i] += 5.
Built-in functions: len(), list(), min(), max(), sum()
These are functions, written as function(list), not as list.method().
len(L): number of items.list(seq): creates a list from a sequence (string, tuple, range);list()with no argument gives an empty list.min(L)/max(L): smallest / largest item. Items must be comparable (all numbers or all strings); strings are compared alphabetically by character code.sum(L): total of numeric items. It does not work on a list of strings.
marks = [72, 88, 95, 61, 79]
print(len(marks), min(marks), max(marks), sum(marks))
print("Average:", sum(marks) / len(marks))
print(list(range(1, 6)), list("abc"))
fruits = ["mango", "apple", "kiwi", "banana"]
print(min(fruits), max(fruits))
print(sum(["a", "b"]))5 61 95 395 Average: 79.0 [1, 2, 3, 4, 5] ['a', 'b', 'c'] apple mango TypeError: unsupported operand type(s) for +: 'int' and 'str'
max([5, "6"]) raises TypeError because an int cannot be compared with a string. Questions sometimes test this.
Adding elements: append() and insert()
L.append(x)adds one itemxat the end of the list. Ifxis a list, the whole list is added as one item (a nested list).L.insert(i, x)insertsxbefore indexi; items fromionward shift right. Ifiis beyond the end, the item is added at the end.
Both methods change the list in place and return None.
Enrichment: L.extend(seq) adds each item of another sequence at the end. It is in NCERT but not named in the CBSE syllabus.
queue = ["Asha", "Bilal"]
queue.append("Chetan")
print(queue)
queue.insert(1, "Diya")
print(queue)
queue.insert(100, "Esha")
print(queue)
queue.append(["Farhan", "Gita"])
print(queue, len(queue))
nums = [1, 2]
nums.extend([3, 4])
print(nums)['Asha', 'Bilal', 'Chetan'] ['Asha', 'Diya', 'Bilal', 'Chetan'] ['Asha', 'Diya', 'Bilal', 'Chetan', 'Esha'] ['Asha', 'Diya', 'Bilal', 'Chetan', 'Esha', ['Farhan', 'Gita']] 6 [1, 2, 3, 4]
A common output-prediction trap: L.append([7, 8]) increases the length by 1, while L.extend([7, 8]) increases it by 2.
Searching and counting: count() and index()
L.count(x)returns how many timesxoccurs in the list (0 if it is not there).L.index(x)returns the index of the first occurrence ofx. Ifxis not in the list it raisesValueError, so check withinfirst.
Note: the NCERT table names this method find() in one place, but lists do not have a find() method; the correct method for lists is index().
votes = ["A", "B", "A", "C", "A", "B"]
print(votes.count("A"), votes.count("D"))
print(votes.index("B"), votes.index("C"))
if "D" in votes:
print(votes.index("D"))
else:
print("D not found")
print(votes.index("D"))3 0 1 3 D not found ValueError: list.index(x): x not in list
Removing elements: remove(), pop() and del
L.remove(x)deletes the first occurrence of the valuex. RaisesValueErrorifxis absent. ReturnsNone.L.pop(i)deletes the item at indexiand returns it. Without an argument,pop()removes and returns the last item. RaisesIndexErrorfor a wrong index or an empty list.del L[i](a statement, not a method) deletes the item at indexi;del L[i:j]deletes a slice, anddel Ldeletes the whole list variable.
Remember: remove works by value, pop and del work by position.
bag = ["pen", "book", "eraser", "book", "ruler", "tiffin"]
bag.remove("book") # first "book" only
print(bag)
last = bag.pop() # removes last item
print(last, bag)
item = bag.pop(1) # removes index 1
print(item, bag)
del bag[0]
print(bag)
bag.remove("pencil")['pen', 'eraser', 'book', 'ruler', 'tiffin'] tiffin ['pen', 'eraser', 'book', 'ruler'] eraser ['pen', 'book', 'ruler'] ['book', 'ruler'] ValueError: list.remove(x): x not in list
Since pop() returns the removed item, it can be stored or printed. remove() returns None, so x = L.remove(5) stores None in x.
Arranging items: reverse() and sort()
L.reverse()reverses the order of items in place.L.sort()arranges the items in ascending order in place.L.sort(reverse=True)arranges them in descending order. Strings are sorted by character code, so uppercase letters come before lowercase.
Both methods change the original list and return None. So print(L.sort()) prints None, and L = L.sort() destroys the list.
Enrichment: the built-in function sorted(L) returns a new sorted list and leaves L unchanged.
heights = [152, 168, 145, 171, 160]
heights.sort()
print(heights)
heights.sort(reverse=True)
print(heights)
heights.reverse()
print(heights)
names = ["ravi", "Zoya", "amit", "Bhanu"]
names.sort()
print(names)
print(heights.sort())
original = [3, 1, 2]
print(sorted(original), original)[145, 152, 160, 168, 171] [171, 168, 160, 152, 145] [145, 152, 160, 168, 171] ['Bhanu', 'Zoya', 'amit', 'ravi'] None [1, 2, 3] [3, 1, 2]
Ask: "What is printed by print([4, 1, 3].sort())?" The answer None surprises most students and is a common MCQ.
Summary of list methods and functions
All list methods and functions named in the CBSE 2025-26 syllabus are summarised below. Methods are called with a dot (L.append(5)); functions take the list as an argument (len(L)).
| Method / function | What it does | Example (L = [30, 10, 20, 10]) | Result |
|---|---|---|---|
len(L) | Number of items | len(L) | 4 |
list(seq) | Creates a list from a sequence | list("ab") | ['a', 'b'] |
append(x) | Adds x at the end | L.append(5) | L becomes [30, 10, 20, 10, 5] |
insert(i, x) | Inserts x before index i | L.insert(0, 5) | L becomes [5, 30, 10, 20, 10] |
count(x) | Number of times x occurs | L.count(10) | 2 |
index(x) | Index of first x (ValueError if absent) | L.index(20) | 2 |
remove(x) | Deletes first x by value | L.remove(10) | L becomes [30, 20, 10] |
pop(i) / pop() | Deletes and returns item at i / last item | L.pop(0) | returns 30; L becomes [10, 20, 10] |
reverse() | Reverses in place | L.reverse() | L becomes [10, 20, 10, 30] |
sort() | Sorts in place (ascending; reverse=True for descending) | L.sort() | L becomes [10, 10, 20, 30] |
min(L) | Smallest item | min(L) | 10 |
max(L) | Largest item | max(L) | 30 |
sum(L) | Sum of numeric items | sum(L) | 70 |
L = [30, 10, 20, 10]
print(len(L), L.count(10), L.index(20), min(L), max(L), sum(L))
for call in ["append(5)", "insert(0, 5)", "remove(10)", "pop(0)", "reverse()", "sort()"]:
L = [30, 10, 20, 10]
result = eval("L." + call)
print(call.ljust(13), "returns", str(result).ljust(5), "L =", L)4 2 2 10 30 70 append(5) returns None L = [30, 10, 20, 10, 5] insert(0, 5) returns None L = [5, 30, 10, 20, 10] remove(10) returns None L = [30, 20, 10] pop(0) returns 30 L = [10, 20, 10] reverse() returns None L = [10, 20, 10, 30] sort() returns None L = [10, 10, 20, 30]
Each row of the table is checked by the program shown here: it starts every method on a fresh copy of [30, 10, 20, 10]. (eval() is used only to keep the demo short; students do not need it.)
List manipulation programs
Most board and practical questions combine input(), a loop and list methods. A typical pattern:
- Create an empty list.
- Use a loop to read values and
append()them. - Traverse the list to calculate, count or search.
The program below reads the marks of n students, then prints the class average, the students above average and the result of a linear search (checking items one by one) for a given mark.
n = int(input("How many students? "))
marks = []
for i in range(n):
m = int(input("Enter marks: "))
marks.append(m)
avg = sum(marks) / len(marks)
print("Marks:", marks)
print("Class average:", avg)
above = []
for m in marks:
if m > avg:
above.append(m)
print("Above average:", above)
key = int(input("Marks to search: "))
found = False
for i in range(len(marks)):
if marks[i] == key:
print(key, "found at position", i + 1)
found = True
break
if not found:
print(key, "not found")How many students? 5 Enter marks: 67 Enter marks: 82 Enter marks: 45 Enter marks: 90 Enter marks: 73 Marks: [67, 82, 45, 90, 73] Class average: 71.4 Above average: [82, 90, 73] Marks to search: 45 45 found at position 3
Encourage students to write the search loop themselves before showing that key in marks and marks.index(key) do the same job. Examiners often ask for the loop version.
Introduction to dictionaries
A dictionary (dict) stores data as key-value pairs. Each key is linked to a value, just as a word in a printed dictionary is linked to its meaning. Example: {"Rajasthan": "Jaipur", "Kerala": "Thiruvananthapuram"}.
Rules and features:
- Items are written inside curly braces
{ }; each item iskey: value, separated by commas. - Keys must be unique. If a key is repeated, the later value replaces the earlier one.
- Keys must be of an immutable type (int, float, string, tuple). A list cannot be a key.
- Values can be of any type and may repeat.
- A dictionary is mutable: items can be added, changed or deleted.
- Items are accessed by key, not by position. (In Python 3.7 and later, items are kept in the order they were inserted.)
capitals = {"Rajasthan": "Jaipur", "Kerala": "Thiruvananthapuram", "Assam": "Dispur"}
print(capitals)
roll = {1: "Ishaan", 2: "Mehak", 1: "Kabir"} # duplicate key 1
print(roll)
bad = {["a", "b"]: 5}{'Rajasthan': 'Jaipur', 'Kerala': 'Thiruvananthapuram', 'Assam': 'Dispur'}
{1: 'Kabir', 2: 'Mehak'}
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')Ask students for real-life key-value data: roll number and name, PIN code and post office, vehicle number and owner. This makes the idea of a unique key obvious. (The exact wording of the list-as-key error differs between Python versions; older versions print TypeError: unhashable type: 'list'.)
Creating and initialising a dictionary
Ways to create a dictionary:
- Empty dictionary:
d = {}ord = dict() - With items in braces:
d = {"MI": 5, "CSK": 5, "KKR": 3} - Using
dict()with keyword arguments (keys become strings):dict(gold=2, silver=5) - Using
dict()with a list of (key, value) pairs:dict([("Mon", 1), ("Tue", 2)]) - Starting empty and adding items one by one in a loop, for example from user input.
d1 = {}
d2 = dict()
titles = {"MI": 5, "CSK": 5, "KKR": 3}
medals = dict(gold=2, silver=5, bronze=1)
days = dict([("Mon", 1), ("Tue", 2), ("Wed", 3)])
print(d1, d2, type(d2))
print(titles)
print(medals)
print(days)
stock = {}
for item, qty in [("pen", 40), ("notebook", 25)]:
stock[item] = qty
print(stock){} {} <class 'dict'>
{'MI': 5, 'CSK': 5, 'KKR': 3}
{'gold': 2, 'silver': 5, 'bronze': 1}
{'Mon': 1, 'Tue': 2, 'Wed': 3}
{'pen': 40, 'notebook': 25}Point out that {} creates an empty dictionary, not an empty set. This comes up as an MCQ.
Accessing items and membership
A value is accessed by writing its key in square brackets: d[key]. If the key does not exist, Python raises KeyError.
The membership operators in and not in check keys only, not values. To check a value, use x in d.values().
Enrichment: d.get(key) returns the value if the key exists and None (or a default you give, as in d.get(key, 0)) if it does not, instead of raising an error.
pin = {"Shimla": 171001, "Ranchi": 834001, "Patna": 800001}
print(pin["Ranchi"])
print("Patna" in pin, 834001 in pin, 834001 in pin.values())
print(pin.get("Goa"), pin.get("Goa", "Not listed"))
print(pin["Goa"])834001 True False True None Not listed KeyError: 'Goa'
Updating and deleting: assignment, update(), del and clear()
Since a dictionary is mutable:
- Add a new item:
d[new_key] = value. - Modify an existing item:
d[existing_key] = new_value(the same syntax; Python adds or replaces depending on whether the key exists). d.update(d2)adds all items of dictionaryd2tod; for keys already ind, the values are replaced by those ind2.del d[key]deletes the item with that key (KeyErrorif absent).del ddeletes the whole dictionary variable; usingdafterwards givesNameError.d.clear()removes all items but keeps the (now empty) dictionary.
The syllabus writes del(), but del is actually a statement, written without brackets: del d["x"].
Enrichment: d.pop(key) deletes the item and returns its value.
fees = {"Class 9": 3200, "Class 10": 3400}
fees["Class 11"] = 3800 # add
fees["Class 9"] = 3300 # modify
print(fees)
fees.update({"Class 12": 4000, "Class 10": 3500})
print(fees)
del fees["Class 9"]
print(fees)
removed = fees.pop("Class 12")
print(removed, fees)
fees.clear()
print(fees, len(fees))
del fees
print(fees){'Class 9': 3300, 'Class 10': 3400, 'Class 11': 3800}
{'Class 9': 3300, 'Class 10': 3500, 'Class 11': 3800, 'Class 12': 4000}
{'Class 10': 3500, 'Class 11': 3800, 'Class 12': 4000}
4000 {'Class 10': 3500, 'Class 11': 3800}
{} 0
NameError: name 'fees' is not definedContrast clear() and del: after clear() the dictionary exists but is empty ({}); after del d the name itself no longer exists.
Traversing a dictionary: keys(), values() and items()
A for loop over a dictionary gives its keys one by one; the value is then d[key].
Three methods return views of the dictionary's contents:
d.keys(): all the keysd.values(): all the valuesd.items(): all the (key, value) pairs as tuples
These can be looped over or converted to a list with list(). Looping over d.items() with two loop variables gives the key and value together.
runs = {"Smriti": 86, "Harmanpreet": 52, "Shafali": 33}
for name in runs:
print(name, "scored", runs[name])
print(runs.keys())
print(runs.values())
print(runs.items())
print(list(runs.keys()))
for name, r in runs.items():
if r >= 50:
print(name, "made a fifty")Smriti scored 86
Harmanpreet scored 52
Shafali scored 33
dict_keys(['Smriti', 'Harmanpreet', 'Shafali'])
dict_values([86, 52, 33])
dict_items([('Smriti', 86), ('Harmanpreet', 52), ('Shafali', 33)])
['Smriti', 'Harmanpreet', 'Shafali']
Smriti made a fifty
Harmanpreet made a fiftyMake sure students can read the dict_keys([...]) style output. It is what Python 3 prints for keys(), values() and items(); older books sometimes show plain lists.
Summary of dictionary methods and functions
All dictionary operations named in the CBSE 2025-26 syllabus:
| Method / function | What it does | Example (d = {"a": 1, "b": 2}) | Result |
|---|---|---|---|
dict() | Creates a dictionary | dict([("x", 9)]) | {'x': 9} |
len(d) | Number of key-value pairs | len(d) | 2 |
keys() | All keys | d.keys() | dict_keys(['a', 'b']) |
values() | All values | d.values() | dict_values([1, 2]) |
items() | All (key, value) pairs | d.items() | dict_items([('a', 1), ('b', 2)]) |
update(d2) | Adds/replaces items from d2 | d.update({"b": 5, "c": 3}) | d becomes {'a': 1, 'b': 5, 'c': 3} |
del d[k] | Deletes the item with key k | del d["a"] | d becomes {'b': 2} |
clear() | Removes all items | d.clear() | d becomes {} |
get(k) (Enrichment) | Value for k, or None if absent | d.get("z") | None |
d = {"a": 1, "b": 2}
print(dict([("x", 9)]), len(d))
print(d.keys(), d.values(), d.items())
d.update({"b": 5, "c": 3}); print(d)
d = {"a": 1, "b": 2}; del d["a"]; print(d)
d = {"a": 1, "b": 2}; d.clear(); print(d)
d = {"a": 1, "b": 2}; print(d.get("z")){'x': 9} 2
dict_keys(['a', 'b']) dict_values([1, 2]) dict_items([('a', 1), ('b', 2)])
{'a': 1, 'b': 5, 'c': 3}
{'b': 2}
{}
NoneManipulating dictionaries: programs
Two patterns appear again and again:
1. Counting frequency. Start with an empty dictionary; for each item, if it is already a key increase its count, otherwise add it with count 1.
2. Building a record book from input. Read a key and a value in a loop and store d[key] = value, then traverse to report.
word = "MISSISSIPPI"
freq = {}
for ch in word:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq)
n = int(input("Number of employees: "))
salary = {}
for i in range(n):
name = input("Name: ")
salary[name] = int(input("Monthly salary: "))
for name in salary:
print(name, "- annual salary Rs", salary[name] * 12){'M': 1, 'I': 4, 'S': 4, 'P': 2}
Number of employees: 2
Name: Neha
Monthly salary: 42000
Name: Arjun
Monthly salary: 38500
Neha - annual salary Rs 504000
Arjun - annual salary Rs 462000List vs dictionary
Choose a list when the order of items matters and items are identified by position (marks of 40 students in roll order). Choose a dictionary when each value has a meaningful label (state and capital, item and price).
| List | Dictionary |
|---|---|
| Ordered collection of items | Collection of key-value pairs |
Written in square brackets [ ] | Written in curly braces { } |
Items accessed by integer index: L[2] | Values accessed by key: d["Kerala"] |
| Duplicate items allowed | Keys must be unique; values may repeat |
| Any type of item | Keys must be immutable; values can be any type |
append(), insert() to add | d[key] = value or update() to add |
Wrong index gives IndexError | Missing key gives KeyError |
Key terms
- List
- An ordered, mutable sequence of items enclosed in square brackets.
- Element (item)
- A single value stored in a list.
- Index
- The position number of an item; starts at 0 from the left and -1 from the right.
- Nested list
- A list that contains another list as one of its items.
- Concatenation
- Joining two lists with the + operator to form a new list.
- Repetition
- Repeating a list a given number of times with the * operator.
- Slicing
- Extracting part of a list using L[start:stop:step]; stop is excluded.
- Traversing
- Visiting every item of a list or dictionary once, usually with a loop.
- Aliasing
- Two names referring to the same list, so a change through one is seen through the other.
- Method
- A function that belongs to an object and is called with a dot, such as L.sort().
- Linear search
- Searching for a value by checking the items of a list one by one.
- Dictionary
- A mutable collection of key-value pairs enclosed in curly braces.
- Key
- The unique, immutable label used to access a value in a dictionary.
- Value
- The data associated with a key in a dictionary; can be of any type.
- Key-value pair
- One item of a dictionary, written as key: value.
- IndexError
- Runtime error raised when a list index is outside the valid range.
- KeyError
- Runtime error raised when a key that does not exist is accessed in a dictionary.
- Frequency count
- A dictionary that records how many times each item occurs.
MCQs
Tap an option to check it, or use Show answers above to reveal them all.
-
Which of the following creates an empty list?
Answer(b) list()
list()(or[]) creates an empty list.{}is an empty dictionary and()an empty tuple. -
What is the output of the following code?
Python towns = ["Agra", "Kota", "Pune"] print(towns[-2])Answer(c) Kota
Index -2 refers to the second-last item.
-
What is the output of the following code?
Python L = [10, 20, 30, 40, 50] print(L[1:3])Answer(c) [20, 30]
The slice includes index 1 and 2 but not 3.
-
What is the output of the following code?
Python print([1, 2] * 2)Answer(a) [1, 2, 1, 2]
*repeats the list. -
Which method adds an item at a specified position in a list?
Answer(d) insert()
insert(index, item)places the item before the given index. Lists do not haveadd()orupdate(). -
What is the output of the following code?
Python nums = [9, 2, 5] print(nums.sort())Answer(a) None
sort()sorts in place and returnsNone, which is what gets printed. -
What is the output of the following code?
Python L = [1, 2, 3, 4] L.append([5, 6]) print(len(L))Answer(b) 5
append()adds the inner list[5, 6]as a single item, so the length becomes 4 + 1 = 5. -
L = [4, 7, 4, 9, 4]. What doesL.index(4)return?Python L = [4, 7, 4, 9, 4] print(L.index(4))Answer(d) 0
index()returns the position of the first occurrence, which is 0. -
Which statement removes the last element of list
Land returns it?Answer(c) L.pop()
pop()without an argument removes and returns the last item.delremoves it but returns nothing, andremove()needs a value. -
What is the output of the following code?
Python L = [3, 4, 1, 4] L.remove(4) print(L)Answer(b) [3, 1, 4]
remove(4)deletes only the first occurrence of 4. -
What is the output of the following code?
Python print(list("Pune"))Answer(d) ['P', 'u', 'n', 'e']
list()on a string makes a list of its characters. -
What is the output of the following code?
Python t1 = ["A", "B", "C"] t2 = t1 t2[0] = "X" print(t1, t2)Answer(c) ['X', 'B', 'C'] ['X', 'B', 'C']
t2 = t1creates an alias, so both names show the change. -
Which of the following cannot be used as a dictionary key?
Answer(a) [1, 2]
Keys must be immutable. A list is mutable, so using it as a key gives a
TypeError(unhashable type: 'list'). -
What is the output of the following code?
Python d = {'a': 1, 'b': 2, 'a': 3} print(d)Answer(b) {'a': 3, 'b': 2}
Keys are unique; the later value 3 replaces 1 for key 'a', which keeps its original position.
-
d = {"Goa": "Panaji", "Bihar": "Patna"}. What is the value of"Patna" in d?Python d = {"Goa": "Panaji", "Bihar": "Patna"} print("Patna" in d)Answer(b) False
inchecks keys only. "Patna" is a value, not a key. -
Which error is raised when you access a key that is not present in a dictionary using
d[key]?Answer(d) KeyError
A missing key raises
KeyError. -
What is the output of the following code?
Python d = {'x': 10, 'y': 20} d.update({'y': 30, 'z': 40}) print(d)Answer(a) {'x': 10, 'y': 30, 'z': 40}
update()replaces the value of the existing key 'y' and adds the new key 'z'. -
Which statement empties a dictionary
dbut keeps it in existence?Answer(d) d.clear()
clear()removes all items, leaving{}.del dremoves the variable itself. -
What is the output of the following code?
Python marks = {'Eng': 78, 'Maths': 92, 'IP': 95} print(len(marks))Answer(a) 3
len()counts key-value pairs: there are 3 keys. -
What does
d.items()return ford = {1: 'one', 2: 'two'}?Python d = {1: 'one', 2: 'two'} print(d.items())Answer(c) dict_items([(1, 'one'), (2, 'two')])
items()returns the key-value pairs as tuples.
Assertion–Reason
Assertion (A): After
L = [5, 3, 8]andL.sort(), the statementprint(L)displays[3, 5, 8].Reason (R): The
sort()method returns a new sorted list and leaves the original list unchanged.Answer(C)
A is true. R is false:
sort()sorts the list in place and returnsNone; it issorted()that returns a new list.Assertion (A): A list can be used as a key in a dictionary.
Reason (R): Dictionary keys must be of an immutable data type.
Answer(D)
A is false because lists are mutable. R is true and is the very reason why A is false.
Assertion (A):
L.pop()can be used in an expression such asx = L.pop().Reason (R):
pop()returns the element it removes from the list.Answer(A)
Both are true, and because
pop()returns the removed item, its result can be assigned to a variable.Assertion (A): For
d = {"a": 1}, the statementd["b"] = 2raises aKeyError.Reason (R): Assigning to a key that does not exist adds a new key-value pair to the dictionary.
Answer(D)
A is false: no error occurs; the pair 'b': 2 is added. R is true.
Assertion (A): Elements of a list can be accessed using negative indexes.
Reason (R): Lists are mutable.
Answer(B)
Both statements are true, but being mutable has nothing to do with negative indexing.
Short answer
- 2 marks
Differentiate between
append()andinsert()with an example.Answerappend(x)adds an item only at the end of the list:L = [1, 2]; L.append(9)gives[1, 2, 9].insert(i, x)adds an item at a given position:L = [1, 2]; L.insert(0, 9)gives[9, 1, 2]. - 2 marks
Differentiate between
remove()andpop()with an example.Answerremove(x)deletes the first occurrence of the value x and returnsNone:[5, 7, 5].remove(5)leaves[7, 5].pop(i)deletes the item at index i (the last item if i is omitted) and returns it: forL = [5, 7, 9],L.pop(1)returns 7 and leaves[5, 9]. - 2 marks
Predict the output of the following code.
Python L = [12, 5, 8, 20, 3] L.insert(2, 15) L.pop() L.sort(reverse=True) print(L) print(L[1:4], L[-1])AnswerPython L = [12, 5, 8, 20, 3] L.insert(2, 15) L.pop() L.sort(reverse=True) print(L) print(L[1:4], L[-1])Output[20, 15, 12, 8, 5] [15, 12, 8] 5
- 2 marks
For
S = ["Ravi", "Asha", "Mohan", "Zara", "Deep"], write the output of: (a)S[::2](b)S[-3:](c)S[1:4][-1](d)"Asha" in S[2:]AnswerPython S = ["Ravi", "Asha", "Mohan", "Zara", "Deep"] print(S[::2]) print(S[-3:]) print(S[1:4][-1]) print("Asha" in S[2:])Output['Ravi', 'Mohan', 'Deep'] ['Mohan', 'Zara', 'Deep'] Zara False
- 2 marks
Find the errors in the following code and rewrite it correctly. Underline each correction.
Python nums = List[] for i in range(5) nums.Append(i * i) nums = nums.sort print(nums)AnswerCorrections:
List[]→[](an empty list is written[]orlist()); add a colon afterrange(5);Append→append(Python is case-sensitive);nums = nums.sort→nums.sort()(the method must be called with brackets, and its result must not be assigned becausesort()returnsNone). The corrected code is:Python nums = [] for i in range(5): nums.append(i * i) nums.sort() print(nums)Output[0, 1, 4, 9, 16]
- 2 marks
What is a dictionary? Give two differences between a list and a dictionary.
AnswerA dictionary is a mutable collection of key-value pairs enclosed in
{ }, where each unique key is used to access its value.- A list is accessed by integer index (
L[0]); a dictionary is accessed by key (d["Goa"]). - A list can have duplicate items; dictionary keys must be unique (and immutable).
- A list is accessed by integer index (
- 2 marks
Predict the output of the following code.
Python stock = {"pen": 50, "pencil": 80} stock["eraser"] = 30 stock["pen"] = stock["pen"] - 15 del stock["pencil"] print(stock) print(len(stock), list(stock.values()))AnswerPython stock = {"pen": 50, "pencil": 80} stock["eraser"] = 30 stock["pen"] = stock["pen"] - 15 del stock["pencil"] print(stock) print(len(stock), list(stock.values()))Output{'pen': 35, 'eraser': 30} 2 [35, 30] - 2 marks
Differentiate between
del dandd.clear()for a dictionaryd.Answerd.clear()removes all the key-value pairs but the dictionary still exists as an empty dictionary{}.del ddeletes the dictionary variable itself; usingdafter that givesNameError: name 'd' is not defined. - 2 marks
Write the output of the following code.
Python team = {"Sindhu": "Badminton", "Neeraj": "Javelin", "Mirabai": "Weightlifting"} for k in team: print(k[0] + "-" + team[k][:3])AnswerPython team = {"Sindhu": "Badminton", "Neeraj": "Javelin", "Mirabai": "Weightlifting"} for k in team: print(k[0] + "-" + team[k][:3])OutputS-Bad N-Jav M-Wei
- 2 marks
Write a program to create a list of the first 10 even natural numbers using a loop, and print the list and the sum of its elements.
AnswerPython evens = [] for i in range(1, 11): evens.append(2 * i) print(evens) print("Sum:", sum(evens))Output[2, 4, 6, 8, 10, 12, 14, 16, 18, 20] Sum: 110
- 2 marks
Identify the error type and explain the cause: (a)
L = [1, 2, 3]; print(L[3])(b)d = {"a": 1}; print(d["b"])(c)[4, 5].remove(6)(d)d = {[1]: "x"}Answer(a)
IndexError: valid indexes are 0 to 2.(b)
KeyError: the key "b" does not exist.(c)
ValueError: 6 is not in the list.(d)
TypeError: a list is mutable and cannot be a dictionary key. - 2 marks
Write the output of the following code.
Python L = [7, 3, 7, 1, 7] print(L.count(7), L.index(1), max(L) - min(L)) L.reverse() print(L, sum(L))AnswerPython L = [7, 3, 7, 1, 7] print(L.count(7), L.index(1), max(L) - min(L)) L.reverse() print(L, sum(L))Output3 3 6 [7, 1, 7, 3, 7] 25
Long answer
- 3 marks
Explain any three list methods and the functions
min(),max()andsum(), with an example of each. (3 marks)Answerappend(x)adds x at the end:L = [2, 4]; L.append(6)gives[2, 4, 6].count(x)gives the number of times x occurs:[1, 2, 1].count(1)is 2.reverse()reverses the list in place:[1, 2, 3]becomes[3, 2, 1].min(L),max(L)andsum(L)give the smallest item, the largest item and the total. ForL = [12, 7, 30]: 7, 30 and 49.
- 3 marks
Write a program to input a list of
nnumbers and display: the count of even and odd numbers, and a new list containing only the numbers greater than the average. (3 marks)AnswerProgram with a sample run:
Python n = int(input("How many numbers? ")) L = [] for i in range(n): L.append(int(input("Enter number: "))) even = odd = 0 for x in L: if x % 2 == 0: even += 1 else: odd += 1 avg = sum(L) / len(L) big = [] for x in L: if x > avg: big.append(x) print("Even:", even, "Odd:", odd) print("Average:", avg) print("Greater than average:", big)OutputHow many numbers? 6 Enter number: 14 Enter number: 9 Enter number: 22 Enter number: 7 Enter number: 30 Enter number: 5 Even: 3 Odd: 3 Average: 14.5 Greater than average: [22, 30]
- 3 marks
Write a program to input a list and a number. Remove all occurrences of that number from the list and display the updated list and how many items were removed. (3 marks)
Answerremove()deletes only the first occurrence, so it is called in a loop while the value is still present:Python L = [5, 2, 5, 8, 5, 1] print("List:", L) x = int(input("Number to remove: ")) removed = 0 while x in L: L.remove(x) removed += 1 print("Updated list:", L) print("Items removed:", removed)OutputList: [5, 2, 5, 8, 5, 1] Number to remove: 5 Updated list: [2, 8, 1] Items removed: 3
- 3 marks
Write a program to create a dictionary of
nitems and their prices entered by the user. Then display all items costing more than Rs 100 and the total price of all items. (3 marks)AnswerProgram with a sample run:
Python n = int(input("Number of items: ")) price = {} for i in range(n): item = input("Item: ") price[item] = float(input("Price: ")) print("Items above Rs 100:") for item in price: if price[item] > 100: print(item, price[item]) print("Total price:", sum(price.values()))OutputNumber of items: 4 Item: Geometry box Price: 145 Item: Notebook Price: 60 Item: Water bottle Price: 220 Item: Pen Price: 20 Items above Rs 100: Geometry box 145.0 Water bottle 220.0 Total price: 445.0
- 5 marks
Write a program to count the frequency of each word in a sentence entered by the user, using a dictionary. Display each word with its frequency. (5 marks)
Answersplit()breaks the sentence into a list of words. A dictionary counts each word:Python sentence = input("Enter a sentence: ") words = sentence.lower().split() freq = {} for w in words: if w in freq: freq[w] += 1 else: freq[w] = 1 for w, c in freq.items(): print(w, ":", c) print("Distinct words:", len(freq))OutputEnter a sentence: The early bird catches the worm and the worm runs the : 3 early : 1 bird : 1 catches : 1 worm : 2 and : 1 runs : 1 Distinct words: 7
- 5 marks
Consider the dictionary
result = {"Anu": 88, "Bala": 64, "Charu": 91, "Dev": 47}. Write Python statements for the following and show the output: (a) add a new student Esha with 79 marks; (b) increase Dev's marks by 5; (c) delete Bala's record; (d) print the names of students who scored above 80; (e) print the number of students and the class average. (5 marks)AnswerPython result = {"Anu": 88, "Bala": 64, "Charu": 91, "Dev": 47} result["Esha"] = 79 # (a) result["Dev"] = result["Dev"] + 5 # (b) del result["Bala"] # (c) print(result) for name in result: # (d) if result[name] > 80: print(name) print(len(result), sum(result.values()) / len(result)) # (e)Output{'Anu': 88, 'Charu': 91, 'Dev': 52, 'Esha': 79} Anu Charu 4 77.5 - 5 marks
Write a menu-driven program for a library list of book titles with options: 1. Add a book 2. Remove a book 3. Display books in alphabetical order 4. Exit. (5 marks)
AnswerThe menu repeats inside a
while Trueloop until the user chooses 4. A sample run is shown:Python books = ["Wings of Fire", "Godan"] while True: print("1. Add 2. Remove 3. Display 4. Exit") ch = int(input("Choice: ")) if ch == 1: books.append(input("Title to add: ")) elif ch == 2: t = input("Title to remove: ") if t in books: books.remove(t) else: print("Not in list") elif ch == 3: books.sort() for b in books: print(" ", b) elif ch == 4: print("Bye") break else: print("Invalid choice")Output1. Add 2. Remove 3. Display 4. Exit Choice: 1 Title to add: Malgudi Days 1. Add 2. Remove 3. Display 4. Exit Choice: 2 Title to remove: Godan 1. Add 2. Remove 3. Display 4. Exit Choice: 3 Malgudi Days Wings of Fire 1. Add 2. Remove 3. Display 4. Exit Choice: 4 Bye
- 3 marks
Explain with examples: (a) indexing and slicing of a list, (b) traversing a dictionary with
items(). (3 marks)Answer(a) Indexing gets one item by position: for
L = [10, 20, 30, 40],L[1]is 20 andL[-1]is 40. Slicing gets a sub-list:L[1:3]is[20, 30](stop excluded) andL[::-1]is the reversed list.(b)
items()gives (key, value) pairs, which can be unpacked in aforloop:Python price = {"Tea": 15, "Samosa": 20} for item, rate in price.items(): print(item, "costs Rs", rate)OutputTea costs Rs 15 Samosa costs Rs 20
Case-based
Mr. Iyer, the PT teacher, recorded the 100 m race times (in seconds) of eight students in a list: times = [14.2, 13.8, 15.1, 12.9, 14.6, 13.5, 16.0, 13.8]. He wants to use Python list methods and functions to analyse the data.
- 1 mark
Write a statement to display the fastest time.
Answerprint(min(times))displays12.9. - 1 mark
How many students ran 13.8 seconds? Write the statement.
Answertimes.count(13.8)gives 2. - 1 mark
Write statements to arrange the times from fastest to slowest and display the top three.
AnswerPython times = [14.2, 13.8, 15.1, 12.9, 14.6, 13.5, 16.0, 13.8] times.sort() print(times[:3])Output[12.9, 13.5, 13.8]
- 1 mark
A ninth student ran 14.0 seconds. Add this time and print the new average, rounded to 2 decimal places.
AnswerPython times = [14.2, 13.8, 15.1, 12.9, 14.6, 13.5, 16.0, 13.8] times.append(14.0) print(round(sum(times) / len(times), 2))Output14.21
A travel agency stores the number of tourists who visited some states last month in a dictionary: visits = {"Goa": 5200, "Kerala": 4100, "Rajasthan": 6300, "Sikkim": 1800}.
- 1 mark
Write a statement to add "Ladakh" with 2500 visitors.
Answervisits["Ladakh"] = 2500 - 1 mark
Kerala's figure was wrongly entered; it should be 4600. Write the statement using
update().Answervisits.update({"Kerala": 4600}) - 2 marks
Write a loop to find and print the state with the highest number of visitors (without using
max()).AnswerPython visits = {"Goa": 5200, "Kerala": 4600, "Rajasthan": 6300, "Sikkim": 1800, "Ladakh": 2500} top = "" highest = 0 for state in visits: if visits[state] > highest: highest = visits[state] top = state print(top, highest)OutputRajasthan 6300
Kunal wrote this code to keep a shopping list but is confused by the output.
cart = ["rice", "dal", "oil"]
backup = cart
cart.append("salt")
new_cart = cart.sort()
print(backup)
print(new_cart)['dal', 'oil', 'rice', 'salt'] None
- 1 mark
Why does
backupalso show "salt"?Answerbackup = cartmakesbackupan alias of the same list, not a copy. Any change throughcartis seen throughbackup. - 1 mark
Why is
new_cartprinted asNone?Answersort()sorts the list in place and returnsNone, and thatNonewas stored innew_cart. - 1 mark
Rewrite lines 2 and 4 so that
backupkeeps the original three items andnew_cartholds a sorted list.Answerbackup = list(cart)(orcart[:]) andnew_cart = sorted(cart)(or callcart.sort()and thennew_cart = cart).
Practicals
1Largest and smallest in a list
Input n numbers into a list. Find the largest and the smallest numbers and their positions (1-based) using a loop, without using max() and min(). Then verify the result using the built-in functions.
n = int(input("How many numbers? "))
L = []
for i in range(n):
L.append(int(input("Enter number: ")))
large = small = L[0]
lpos = spos = 0
for i in range(1, len(L)):
if L[i] > large:
large, lpos = L[i], i
if L[i] < small:
small, spos = L[i], i
print("List:", L)
print("Largest:", large, "at position", lpos + 1)
print("Smallest:", small, "at position", spos + 1)
print("Check with max()/min():", max(L), min(L))How many numbers? 6 Enter number: 45 Enter number: -8 Enter number: 102 Enter number: 37 Enter number: 0 Enter number: 88 List: [45, -8, 102, 37, 0, 88] Largest: 102 at position 3 Smallest: -8 at position 2 Check with max()/min(): 102 -8
Viva questions (2)
- Why are
largeandsmallinitialised withL[0]and not 0? If all numbers are negative (or all positive), 0 would give a wrong answer. - Why does the loop start from index 1? Index 0 is already used for the starting values.
2Third largest and third smallest
Input a list of numbers (duplicates allowed). Display the third largest and third smallest distinct values. Show a message if there are fewer than three distinct values.
L = eval(input("Enter a list of numbers: "))
unique = []
for x in L:
if x not in unique:
unique.append(x)
unique.sort()
if len(unique) < 3:
print("Fewer than three distinct values")
else:
print("Distinct values sorted:", unique)
print("Third smallest:", unique[2])
print("Third largest:", unique[-3])Enter a list of numbers: [56, 12, 89, 56, 34, 89, 7, 71] Distinct values sorted: [7, 12, 34, 56, 71, 89] Third smallest: 34 Third largest: 56
Viva questions (3)
- Why are duplicates removed first? Otherwise a repeated value could be counted twice as 'largest' and 'second largest'.
- What does
unique[-3]give? The third item from the end, which is the third largest in an ascending list. - What does
eval(input())do here? It turns the typed text[56, 12, ...]into a real list.
3Menu-driven list operations
Start with the list of runs [45, 12, 78]. Display a menu that lets the user: 1. append a score, 2. insert a score at a position, 3. delete a score by value, 4. delete a score by position (and show it), 5. sort in descending order, 6. show count, total and highest, 7. exit.
runs = [45, 12, 78]
while True:
print("1.Append 2.Insert 3.Remove 4.Pop 5.Sort desc 6.Stats 7.Exit")
ch = int(input("Choice: "))
if ch == 1:
runs.append(int(input("Score: ")))
elif ch == 2:
pos = int(input("Position (index): "))
runs.insert(pos, int(input("Score: ")))
elif ch == 3:
s = int(input("Score to remove: "))
if s in runs:
runs.remove(s)
else:
print("Not found")
elif ch == 4:
pos = int(input("Index to delete: "))
if 0 <= pos < len(runs):
print("Deleted:", runs.pop(pos))
else:
print("Invalid index")
elif ch == 5:
runs.sort(reverse=True)
elif ch == 6:
print("Innings:", len(runs), "Total:", sum(runs), "Highest:", max(runs))
elif ch == 7:
break
else:
print("Invalid choice")
print("Runs:", runs)1.Append 2.Insert 3.Remove 4.Pop 5.Sort desc 6.Stats 7.Exit Choice: 1 Score: 101 Runs: [45, 12, 78, 101] 1.Append 2.Insert 3.Remove 4.Pop 5.Sort desc 6.Stats 7.Exit Choice: 2 Position (index): 1 Score: 33 Runs: [45, 33, 12, 78, 101] 1.Append 2.Insert 3.Remove 4.Pop 5.Sort desc 6.Stats 7.Exit Choice: 4 Index to delete: 2 Deleted: 12 Runs: [45, 33, 78, 101] 1.Append 2.Insert 3.Remove 4.Pop 5.Sort desc 6.Stats 7.Exit Choice: 5 Runs: [101, 78, 45, 33] 1.Append 2.Insert 3.Remove 4.Pop 5.Sort desc 6.Stats 7.Exit Choice: 6 Innings: 4 Total: 257 Highest: 101 Runs: [101, 78, 45, 33] 1.Append 2.Insert 3.Remove 4.Pop 5.Sort desc 6.Stats 7.Exit Choice: 7
Viva questions (3)
- Why is
inchecked beforeremove()?remove()raisesValueErrorif the value is absent. - What does
pop(pos)return? The deleted item, which is printed. - How does the loop end?
breakruns when the user chooses 7.
4Words starting with a given letter
Input a sentence and a letter. Display all words of the sentence that start with that letter (ignore case), and the number of such words.
sentence = input("Enter a sentence: ")
letter = input("Enter a letter: ")
words = sentence.split()
selected = []
for w in words:
if w[0].lower() == letter.lower():
selected.append(w)
print("Words starting with", letter, ":", selected)
print("Count:", len(selected))Enter a sentence: Sachin scored six sixes in Sharjah stadium Enter a letter: s Words starting with s : ['Sachin', 'scored', 'six', 'sixes', 'Sharjah', 'stadium'] Count: 6
Viva questions (2)
- What does
split()return? A list of the words in the string, split at spaces. - Why is
lower()used on both sides? So that 'S' and 's' are treated as the same letter.
5Occurrences of a letter in each string
Store the names of five rivers in a list. Input a letter and display how many times it occurs in each name, and the total.
rivers = ["Ganga", "Yamuna", "Narmada", "Godavari", "Kaveri"]
letter = input("Enter a letter: ")
total = 0
for r in rivers:
c = r.lower().count(letter.lower())
print(r, ":", c)
total += c
print("Total occurrences:", total)Enter a letter: a Ganga : 2 Yamuna : 2 Narmada : 3 Godavari : 2 Kaveri : 1 Total occurrences: 10
Viva questions (2)
- Which method counts a character in a string?
count(), which also exists for lists. - What is the difference between
L.count(x)ands.count(x)? The first counts items in a list, the second counts characters or substrings in a string.
6States and capitals dictionary
Create a dictionary of five states and their capitals by taking input from the user. Display all the pairs, then input a state and display its capital, or a message if it is not in the dictionary.
capitals = {}
for i in range(5):
state = input("State: ")
capitals[state] = input("Capital: ")
print("\nState - Capital")
for state, cap in capitals.items():
print(state, "-", cap)
q = input("Search capital of: ")
if q in capitals:
print("Capital of", q, "is", capitals[q])
else:
print(q, "is not in the dictionary")State: Punjab Capital: Chandigarh State: Odisha Capital: Bhubaneswar State: Gujarat Capital: Gandhinagar State: Manipur Capital: Imphal State: Telangana Capital: Hyderabad State - Capital Punjab - Chandigarh Odisha - Bhubaneswar Gujarat - Gandhinagar Manipur - Imphal Telangana - Hyderabad Search capital of: Gujarat Capital of Gujarat is Gandhinagar
Viva questions (2)
- Why is
inused beforecapitals[q]? To avoid aKeyErrorfor a state that is not stored. - What will happen if the same state is entered twice? The later capital replaces the earlier one because keys are unique.
7Student marks dictionary
Create a dictionary where each key is a student's name and the value is a list of marks in 5 subjects. Display each student's total and percentage, and the name of the student with the highest total.
n = int(input("Number of students: "))
record = {}
for i in range(n):
name = input("Name: ")
marks = []
for j in range(5):
marks.append(int(input(" Marks in subject " + str(j + 1) + ": ")))
record[name] = marks
topper = ""
best = -1
for name, marks in record.items():
total = sum(marks)
print(name, marks, "Total:", total, "Percentage:", total / 5)
if total > best:
best, topper = total, name
print("Topper:", topper, "with", best)Number of students: 2 Name: Tanvi Marks in subject 1: 88 Marks in subject 2: 92 Marks in subject 3: 79 Marks in subject 4: 95 Marks in subject 5: 90 Name: Rohan Marks in subject 1: 76 Marks in subject 2: 85 Marks in subject 3: 91 Marks in subject 4: 68 Marks in subject 5: 80 Tanvi [88, 92, 79, 95, 90] Total: 444 Percentage: 88.8 Rohan [76, 85, 91, 68, 80] Total: 400 Percentage: 80.0 Topper: Tanvi with 444
Viva questions (2)
- What is the data type of each value in
record? A list of five integers. - How is the percentage worked out? Total divided by 500, multiplied by 100, which is the same as total / 5.
8Highest and lowest values in a dictionary
Given a dictionary of players and their runs in a season, display the player with the highest runs and the one with the lowest runs. Also display the highest and lowest values using max() and min() on values().
season = {"Gill": 890, "Rahul": 545, "Pant": 612, "Iyer": 430, "Jadeja": 498}
high_name = low_name = None
for player in season:
if high_name is None or season[player] > season[high_name]:
high_name = player
if low_name is None or season[player] < season[low_name]:
low_name = player
print("Highest:", high_name, season[high_name])
print("Lowest:", low_name, season[low_name])
print("Check:", max(season.values()), min(season.values()))Highest: Gill 890 Lowest: Iyer 430 Check: 890 430
Viva questions (2)
- What does
max(season)return without.values()? The largest key alphabetically, not the highest runs. - Why is
is Noneused in the conditions? So that the first player is taken as the starting value.
Common mistakes
Assigning the result of
sort(),reverse(),append()orinsert()back to the list, as inL = L.sort(). These methods change the list in place and returnNone, soLbecomesNone. Just writeL.sort().Confusing
remove()withpop().remove(x)deletes by value;pop(i)deletes by index and returns the item.Using
L[len(L)]for the last item. Valid indexes end atlen(L) - 1; useL[-1].Writing
L + 5to add an item.+joins two lists, so writeL + [5]orL.append(5).Thinking
list2 = list1makes a copy. It makes an alias; uselist(list1)orlist1[:]for a separate copy.Checking a value with
inon a dictionary.x in dchecks keys only; usex in d.values()for values.Using a list as a dictionary key, which gives a
TypeError(unhashable type: 'list'). Keys must be immutable, so use a string, number or tuple.Accessing a dictionary item by position, as in
d[0], when 0 is not a key. Dictionaries are accessed by key, and this gives aKeyError.