Class | Subject | Book | Chapter | Session | Questions covered |
|---|---|---|---|---|---|
XI | Computer Science | Computer Science (NCERT) | 10 – Tuples and Dictionaries | 2026-27 | 13 of 13 |
Chapter at a glance
Idea | Key point |
|---|---|
Tuple | Ordered, immutable sequence in ( ); a single-element tuple needs a comma: (5,) |
Tuple operations | Indexing, slicing, +, *, in; functions len(), count(), index(), sorted(), min(), max(), sum() |
Tuple assignment | a, b = b, a; functions return several values as a tuple |
Dictionary | Mutable mapping of unique, immutable keys to values, in {key: value} |
Dictionary methods | get(), keys(), values(), items(), update(), del, pop(), clear(), len() |
Traversal | for k in d: or for k, v in d.items(): |
Order | Python 3.7+ keeps dictionaries in insertion order |
Exercise Questions
Consider the following tuples, tuple1 and tuple2: tuple1 = (23,1,45,67,45,9,55,45), tuple2 = (100,200). Find the output of the following statements:
i. print(tuple1.index(45)) ii. print(tuple1.count(45)) iii. print(tuple1 + tuple2) iv. print(len(tuple2)) v. print(max(tuple1)) vi. print(min(tuple1)) vii. print(sum(tuple2)) viii. print(sorted(tuple1)); print(tuple1)
Answer
Answer
Part | Output | Reason |
|---|---|---|
i | 2 | Index of the first 45 |
ii | 3 | 45 occurs three times |
iii | (23, 1, 45, 67, 45, 9, 55, 45, 100, 200) | Concatenation |
iv | 2 | Two elements |
v | 67 | Largest |
vi | 1 | Smallest |
vii | 300 | 100 + 200 |
viii | [1, 9, 23, 45, 45, 45, 55, 67] then (23, 1, 45, 67, 45, 9, 55, 45) | sorted() returns a new list; the tuple is unchanged |
- 2 ii) 3 iii) (23, 1, 45, 67, 45, 9, 55, 45, 100, 200) iv) 2 v) 67 vi) 1 vii) 300 viii) [1, 9, 23, 45, 45, 45, 55, 67] and (23, 1, 45, 67, 45, 9, 55, 45)
Consider the following dictionary stateCapital: stateCapital = {"AndhraPradesh":"Hyderabad", "Bihar":"Patna", "Maharashtra":"Mumbai", "Rajasthan":"Jaipur"}. Find the output of the following statements:
i. get("Bihar") ii. keys() iii. values() iv. items() v. len(stateCapital) vi. "Maharashtra" in stateCapital vii. get("Assam") viii. del stateCapital["Rajasthan"]; print(stateCapital)
Answer
Answer
- Patna
- dict_keys(['AndhraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan'])
- dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur'])
- dict_items([('AndhraPradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra', 'Mumbai'), ('Rajasthan', 'Jaipur')])
- 4
- True (membership checks keys)
- None (get() returns None for a missing key instead of raising an error)
- {'AndhraPradesh': 'Hyderabad', 'Bihar': 'Patna', 'Maharashtra': 'Mumbai'}
(The dictionary pairs Andhra Pradesh with Hyderabad as given in the book; Andhra Pradesh’s capital is now Amaravati.)
- Patna ii) dict_keys([…4 states]) iii) dict_values([‘Hyderabad’, ‘Patna’, ‘Mumbai’, ‘Jaipur’]) iv) dict_items([…4 pairs]) v) 4 vi) True vii) None viii) dictionary without Rajasthan
“Lists and Tuples are ordered”. Explain.
Answer
Answer
A sequence is ordered when each element has a fixed position (index) and the elements stay in the order in which they were stored. In lists and tuples:
- Each element can be accessed by its index — L[0] is always the first element.
- Two lists/tuples with the same elements in a different order are not equal: [1, 2] == [2, 1] is False.
- Traversal always visits elements in the same order; slicing depends on positions.
Example: t = ('a', 'b', 'c') — t[1] is always 'b'. (In contrast, a set has no positions.)
Lists and tuples keep elements in a fixed sequence, each with an index; order matters for access, slicing and equality ([1, 2] ≠ [2, 1]).
With the help of an example show how can you return more than one value from a function.
Answer
Answer
A function can return several values separated by commas; Python packs them into a tuple, which can be unpacked into variables.
def stats(L):
return min(L), max(L), sum(L) / len(L)
low, high, avg = stats([4, 9, 2, 7])
print(low, high, avg) # 2 9 5.5
print(stats([4, 9, 2, 7])) # (2, 9, 5.5)
Return comma-separated values (return a, b, c); they are packed into a tuple and can be unpacked: low, high, avg = stats(L).
What advantages do tuples have over lists?
Answer
Answer
- Data safety: tuples are immutable, so their data cannot be changed accidentally — useful for constants such as days of the week.
- Faster: iterating over a tuple is slightly faster than over a list.
- Less memory: tuples take less memory.
- Can be dictionary keys: being immutable (hashable), tuples can be used as dictionary keys or set elements; lists cannot.
- Returning multiple values from functions naturally uses tuples.
Tuples are immutable (data protection), faster, use less memory, and can be used as dictionary keys.
When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.
Answer
Answer
Use a tuple when the data is a fixed collection that should not change:
- Days of the week, months: months = ('Jan', 'Feb', …)
- Coordinates of a point: (x, y); RGB colour (255, 0, 0)
- Returning multiple values from a function
- As a dictionary key: distance[('Delhi', 'Agra')] = 233
Use a dictionary when data must be looked up quickly by a unique key:
- Phone book: name → phone number
- Student records: roll number → (name, marks)
- Counting frequencies of words or letters
- Product prices: item → price
Use tuples for fixed, unchangeable data (days, coordinates, returning multiple values, keys); use dictionaries for key-based lookup (phone book, roll number → record, frequency counts, price lists).
Prove with the help of an example that the variable is rebuilt in case of immutable data types.
Answer
Answer
When an immutable object is “changed”, Python creates a new object and the variable starts referring to it. id() shows the identity (memory address) of an object.
num = 10
print(id(num)) # e.g. 140712834012464
num = num + 5
print(id(num)) # a different id → a new object was created
t = (1, 2, 3)
print(id(t))
t = t + (4,)
print(id(t)) # different id — tuple rebuilt
For a mutable list, L.append(4) keeps the same id(L).
After num = num + 5 (or t = t + (4,)), id() shows a different value, proving a new object was built and the variable rebound, unlike a list, whose id stays the same after append.
TypeError occurs while statement 2 is running. Give reason. How can it be corrected?
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2
Answer
Answer
Reason: (5) is just the integer 5 in parentheses, not a tuple. So tuple1 is an int, and len() cannot be applied to an int → TypeError: object of type 'int' has no len().
Correction: put a comma after the element to make a single-element tuple:
>>> tuple1 = (5,)
>>> len(tuple1)
1
- is an integer, not a tuple, so len() fails; write tuple1 = (5,) with a trailing comma.
Question P1
Write a program to read email IDs of n number of students and store them in a tuple. Create two new tuples, one to store only the usernames from the email IDs and second to store domain names from the email IDs. Print all three tuples at the end of the program. [Hint: You may use the function split()]
Answer
n = int(input("Number of students: "))
emails = ()
for i in range(n):
emails += (input("Enter email ID: "),)
usernames = ()
domains = ()
for e in emails:
user, domain = e.split("@")
usernames += (user,)
domains += (domain,)
print("Emails:", emails)
print("Usernames:", usernames)
print("Domains:", domains)
Sample run: (‘ria@gmail.com’, ‘aman@yahoo.in’) → usernames (‘ria’, ‘aman’), domains (‘gmail.com’, ‘yahoo.in’)
Build the email tuple by concatenation, split each ID at ‘@’ and add the parts to the usernames and domains tuples; print all three.
Question P2
Write a program to input names of n students and store them in a tuple. Also, input a name from the user and find if this student is present in the tuple or not. We can accomplish these by: (a) writing a user defined function (b) using the built-in function
Answer
def search(names, key): # (a) user-defined function
for nm in names:
if nm == key:
return True
return False
n = int(input("Number of students: "))
names = tuple(input("Enter name: ") for i in range(n))
key = input("Name to search: ")
print("(a) Found" if search(names, key) else "(a) Not found")
print("(b) Found" if key in names else "(b) Not found") # (b) built-in 'in'
(names.count(key) > 0 or names.index(key) can also be used.)
- Traverse the tuple comparing each name with the key; (b) use the membership operator key in names (or count()).
Question P3
Write a Python program to find the highest 2 values in a dictionary.
Answer
d = {'a': 45, 'b': 89, 'c': 12, 'd': 76, 'e': 89}
values = sorted(d.values(), reverse=True)
print("Highest two values:", values[0], values[1])
Output: Highest two values: 89 89. To get the two highest distinct values use sorted(set(d.values()), reverse=True)[:2] → 89, 76.
Sort d.values() in descending order and take the first two (use set() for distinct values).
Question P4
Write a Python program to create a dictionary from a string. Note: Track the count of the letters from the string. Sample string: ‘w3resource’. Expected output: {‘3’: 1, ‘s’: 1, ‘r’: 2, ‘u’: 1, ‘w’: 1, ‘c’: 1, ‘e’: 2, ‘o’: 1}
Answer
s = input("Enter a string: ")
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
print(freq)
For ‘w3resource’ Python prints {'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1} — the same key–count pairs as the expected output, shown in order of first appearance.
For each character, freq[ch] = freq.get(ch, 0) + 1; ‘w3resource’ gives r: 2, e: 2 and 1 for every other character.
Question P5
Write a program to input your friends’ names and their Phone Numbers and store them in the dictionary as the key-value pair. Perform the following operations on the dictionary:
a) Display the name and phone number of all your friends b) Add a new key-value pair in this dictionary and display the modified dictionary c) Delete a particular friend from the dictionary d) Modify the phone number of an existing friend e) Check if a friend is present in the dictionary or not f) Display the dictionary in sorted order of names
Answer
phone = {}
n = int(input("Number of friends: "))
for i in range(n):
name = input("Name: ")
phone[name] = input("Phone number: ")
# a) display
for name, num in phone.items():
print(name, ":", num)
# b) add
name = input("New friend's name: ")
phone[name] = input("Phone number: ")
print(phone)
# c) delete
name = input("Friend to delete: ")
if name in phone:
del phone[name]
# d) modify
name = input("Friend whose number changes: ")
if name in phone:
phone[name] = input("New number: ")
# e) check presence
name = input("Friend to search: ")
print("Present" if name in phone else "Not present")
# f) sorted by name
for name in sorted(phone):
print(name, ":", phone[name])
Store name → number; display with items(), add/modify with phone[name] = number, delete with del, check with in, and print sorted(phone) for alphabetical order.
Topic checklist
- ☒ Tuple operations and functions (Q1, 3, 5, 8)
- ☒ Dictionary methods (Q2)
- ☒ Returning multiple values; immutability (Q4, 7)
- ☒ Choosing tuple vs dictionary (Q6)
- ☒ Programs with tuples and dictionaries (P1–P5)