Exercise Solutions Available
Step-by-step answers for all textbook questions in this chapter
How to Use This Page
1. Attempt every exercise on your own before reading the solution. 2. Compare your approach with the solution — focus on the logic, not just the final answer. 3. Type and run the Python code on your computer; reading alone is not enough. 4. Review the Common Mistakes section to avoid errors that cost marks in exams.
Key Concepts
Quick Comparison Table
| Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) | {1, 2, 3} | {"a": 1} |
| Ordered | Yes | Yes | No (Python 3.7+ insertion-ordered) | Yes (Python 3.7+) |
| Mutable | Yes | No | Yes | Yes |
| Duplicates | Allowed | Allowed | Not allowed | Keys unique |
| Indexing | lst[0] | t[0] | No indexing | d["key"] |
| Use case | Collection of items | Fixed collection | Unique items | Key-value pairs |
List Methods
| Method | Description | Example |
|---|---|---|
append(x) | Add x to end | [1].append(2) → [1, 2] |
insert(i, x) | Insert x at index i | [1, 3].insert(1, 2) → [1, 2, 3] |
extend(iter) | Add all items from iterable | [1].extend([2, 3]) → [1, 2, 3] |
pop([i]) | Remove & return item at i (default last) | [1, 2, 3].pop() → 3 |
remove(x) | Remove first occurrence of x | [1, 2, 1].remove(1) → [2, 1] |
sort() | Sort in place | [3, 1, 2].sort() → [1, 2, 3] |
reverse() | Reverse in place | [1, 2, 3].reverse() → [3, 2, 1] |
index(x) | Return index of first x | [1, 2, 3].index(2) → 1 |
count(x) | Count occurrences of x | [1, 2, 1].count(1) → 2 |
clear() | Remove all items | [1, 2].clear() → [] |
Set Operations
| Operation | Operator | Method | Example | ||
|---|---|---|---|---|---|
| Union | `\ | ` | .union() | `{1,2} \ | {2,3} → {1,2,3}` |
| Intersection | & | .intersection() | {1,2} & {2,3} → {2} | ||
| Difference | - | .difference() | {1,2} - {2,3} → {1} | ||
| Symmetric Difference | ^ | .symmetric_difference() | {1,2} ^ {2,3} → {1,3} |
Dictionary Methods
| Method | Description | Example |
|---|---|---|
keys() | Returns view of all keys | d.keys() |
values() | Returns view of all values | d.values() |
items() | Returns view of (key, value) pairs | d.items() |
get(key) | Returns value or None | d.get("a") |
get(key, default) | Returns value or default | d.get("x", 0) |
update(d2) | Merge d2 into d | d.update({"c": 3}) |
pop(key) | Remove key and return value | d.pop("a") |
setdefault(key, val) | Set key if missing | d.setdefault("x", 0) |
Multiple Choice Questions (MCQs)
Q1. Which of the following is an immutable data structure?
- (a) List
- (b) Set
- (c) Tuple
- (d) Dictionary
Q2. What does [1, 2, 3] + [4, 5] produce?
- (a)
[1, 2, 3, 4, 5] - (b)
[5, 7, 3] - (c) Error
- (d)
[1, 2, 3, [4, 5]]
Q3. What is the output of {1, 2, 3} & {2, 3, 4}?
- (a)
{1, 2, 3, 4} - (b)
{2, 3} - (c)
{1, 4} - (d) Error
Q4. What does d.get("x", 0) return if key "x" is not in dictionary d?
- (a) Raises KeyError
- (b) None
- (c) 0
- (d) "0"
Q5. Which method adds a single element to the end of a list?
- (a)
insert() - (b)
extend() - (c)
append() - (d)
add()
Fill in the Blanks
Q1. A ______ is an unordered collection of unique elements.
Q2. The ______ method removes and returns the last element from a list.
Q3. In a dictionary, each entry consists of a ______ and a ______.
Q4. The ______ operator is used for symmetric difference of two sets.
Q5. len({1, 2, 2, 3, 3, 3}) returns ______.
True or False
Q1. A set can contain duplicate elements.
Q2. List slicing creates a new list.
Q3. A tuple with one element can be created as (5,).
Q4. Dictionary keys must be immutable types.
Q5. The sort() method returns a new sorted list.
Match the Following
| Column A | Column B |
|---|---|
1. lst.append(x) | (a) Remove all elements |
2. lst.pop() | (b) Add x to the end |
3. lst.sort() | (c) Sort in ascending order |
4. lst.clear() | (d) Remove & return last element |
5. lst.extend(seq) | (e) Add all items from seq |
Short Answer Questions
Q1. Differentiate between list and tuple.
| Feature | List | Tuple |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutability | Mutable (can change) | Immutable (cannot change) |
| Speed | Slower | Faster |
| Methods | Many (append, pop, sort...) | Few (count, index) |
| Dictionary key | Cannot be a key | Can be a dictionary key |
| Use when | Data changes frequently | Data is constant |
# List — mutable
lst = [1, 2, 3]
lst.append(4) # OK: [1, 2, 3, 4]
lst[0] = 10 # OK: [10, 2, 3, 4]
# Tuple — immutable
tup = (1, 2, 3)
# tup.append(4) # Error: tuple has no append
# tup[0] = 10 # Error: tuple does not support assignment
Q2. Explain any five list methods with examples.
lst = [3, 1, 4, 1, 5]
# 1. append — add to end
lst.append(9)
print(lst) # [3, 1, 4, 1, 5, 9]
# 2. insert — add at specific position
lst.insert(2, 99)
print(lst) # [3, 1, 99, 4, 1, 5, 9]
# 3. pop — remove by index
lst.pop() # removes and returns 9
print(lst) # [3, 1, 99, 4, 1, 5]
# 4. remove — remove by value
lst.remove(1) # removes first 1
print(lst) # [3, 99, 4, 1, 5]
# 5. sort — sort in place
lst.sort()
print(lst) # [1, 3, 4, 5, 99]
Q3. What are set operations? Explain with examples.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
# Union — all elements from both sets
print(A | B) # {1, 2, 3, 4, 5, 6}
print(A.union(B)) # {1, 2, 3, 4, 5, 6}
# Intersection — common elements
print(A & B) # {3, 4}
print(A.intersection(B)) # {3, 4}
# Difference — elements in A but not in B
print(A - B) # {1, 2}
print(A.difference(B)) # {1, 2}
# Symmetric Difference — elements in either set but not both
print(A ^ B) # {1, 2, 5, 6}
print(A.symmetric_difference(B)) # {1, 2, 5, 6}
Q4. Explain dictionary methods: get(), update(), pop(), keys(), values(), items().
d = {"name": "Arun", "age": 17}
# get — safe access with default
print(d.get("name")) # Arun
print(d.get("city", "N/A")) # N/A (key not found)
# update — merge another dictionary
d.update({"city": "Chennai", "age": 18})
print(d) # {'name': 'Arun', 'age': 18, 'city': 'Chennai'}
# pop — remove and return value
age = d.pop("age")
print(age) # 18
print(d) # {'name': 'Arun', 'city': 'Chennai'}
# keys, values, items
print(list(d.keys())) # ['name', 'city']
print(list(d.values())) # ['Arun', 'Chennai']
print(list(d.items())) # [('name', 'Arun'), ('city', 'Chennai')]
Q5. What is the difference between append() and extend()?
# append — adds the entire object as one element
a = [1, 2, 3]
a.append([4, 5])
print(a) # [1, 2, 3, [4, 5]] — list inside list
# extend — adds each element from the iterable
b = [1, 2, 3]
b.extend([4, 5])
print(b) # [1, 2, 3, 4, 5] — flat list
Detailed Answers
Q1. Write a Python program to perform list operations: create, append, insert, delete, sort, and reverse.
# Create a list
fruits = ["banana", "apple", "cherry"]
print("Original:", fruits) # ['banana', 'apple', 'cherry']
# Append — add to end
fruits.append("date")
print("After append:", fruits) # ['banana', 'apple', 'cherry', 'date']
# Insert — add at specific position
fruits.insert(1, "avocado")
print("After insert:", fruits) # ['banana', 'avocado', 'apple', 'cherry', 'date']
# Remove by value
fruits.remove("apple")
print("After remove:", fruits) # ['banana', 'avocado', 'cherry', 'date']
# Pop — remove by index
fruits.pop(1)
print("After pop(1):", fruits) # ['banana', 'cherry', 'date']
# Sort
fruits.sort()
print("After sort:", fruits) # ['banana', 'cherry', 'date']
# Reverse
fruits.reverse()
print("After reverse:", fruits) # ['date', 'cherry', 'banana']
Q2. Write a program to find the largest and smallest element in a list without using built-in functions.
def find_max_min(lst):
if not lst:
return None, None
max_val = min_val = lst[0]
for num in lst[1:]:
if num > max_val:
max_val = num
if num < min_val:
min_val = num
return max_val, min_val
numbers = [34, 12, 56, 78, 5, 23]
maximum, minimum = find_max_min(numbers)
print("List:", numbers)
print("Largest:", maximum) # 78
print("Smallest:", minimum) # 5
Q3. Write a program to count the frequency of each element in a list using a dictionary.
def frequency_count(lst):
freq = {}
for item in lst:
freq[item] = freq.get(item, 0) + 1
return freq
numbers = [1, 2, 3, 2, 1, 3, 3, 4, 5, 4, 3]
freq = frequency_count(numbers)
for key, value in sorted(freq.items()):
print(f"{key}: {value}", end=" ")
# Output: 1: 2 2: 2 3: 3 4: 2 5: 1
Q4. Write a program to demonstrate all set operations.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print("Set A:", A)
print("Set B:", B)
print("Union (A | B):", A | B)
# {1, 2, 3, 4, 5, 6, 7, 8}
print("Intersection (A & B):", A & B)
# {4, 5}
print("Difference (A - B):", A - B)
# {1, 2, 3}
print("Symmetric Difference (A ^ B):", A ^ B)
# {1, 2, 3, 6, 7, 8}
# Membership test
print("3 in A:", 3 in A) # True
print("6 in A:", 6 in A) # False
# Add and remove
A.add(10)
print("After add(10):", A)
A.discard(2)
print("After discard(2):", A)
Q5. Write a program to create a dictionary of student marks and perform various operations.
# Create dictionary
marks = {"Tamil": 85, "English": 92, "Maths": 78, "Science": 88}
print("Marks:", marks)
# Access a value
print("Maths mark:", marks["Maths"]) # 78
print("CS mark (safe):", marks.get("CS", "Not found")) # Not found
# Add a new subject
marks["CS"] = 95
print("After adding CS:", marks)
# Update an existing value
marks["Maths"] = 82
print("After updating Maths:", marks)
# Delete a key
del marks["English"]
print("After deleting English:", marks)
# Iterate through dictionary
print("\nAll subjects and marks:")
for subject, mark in marks.items():
print(f" {subject}: {mark}")
# Find total and average
total = sum(marks.values())
average = total / len(marks)
print(f"\nTotal: {total}, Average: {average:.2f}")
# Find highest and lowest
highest = max(marks, key=marks.get)
lowest = min(marks, key=marks.get)
print(f"Highest: {highest} ({marks[highest]})")
print(f"Lowest: {lowest} ({marks[lowest]})")
Q6. Write a program to remove duplicates from a list using a set.
def remove_duplicates(lst):
"""Remove duplicates while preserving order."""
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
# Method 1: Using set (order not preserved)
numbers = [1, 2, 3, 2, 1, 4, 5, 3]
unique_set = list(set(numbers))
print("Using set (unordered):", unique_set)
# Method 2: Preserving order
unique_ordered = remove_duplicates(numbers)
print("Preserving order:", unique_ordered) # [1, 2, 3, 4, 5]
Q7. Write a program to merge two dictionaries.
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
# Method 1: Using update() (modifies dict1)
merged = dict1.copy()
merged.update(dict2)
print("Merged (update):", merged) # {'a': 1, 'b': 3, 'c': 4}
# Method 2: Using ** unpacking (Python 3.5+)
merged2 = {**dict1, **dict2}
print("Merged (unpacking):", merged2) # {'a': 1, 'b': 3, 'c': 4}
# Note: When keys overlap, the later dictionary's value wins
Common Mistakes
| Mistake | Why It's Wrong | Correction |
|---|---|---|
tuple[0] = 5 | Tuples are immutable | Convert to list first or create a new tuple |
{1, 2, 3}[0] | Sets are unordered, no indexing | Convert to list first: list({1,2,3})[0] |
lst = lst.sort() | sort() returns None | Use lst.sort() (in place) or sorted(lst) (returns new list) |
dict["key"] when key missing | Raises KeyError | Use dict.get("key", default) |
(5) as a single-element tuple | This is just the integer 5 | Use (5,) with a trailing comma |
| Using mutable objects as dict keys | Lists/sets cannot be keys | Use tuples or strings as keys |
Confusing append() and extend() | append([1,2]) adds a nested list | Use extend([1,2]) for flat addition |
Exam Checklist
- [ ] I can differentiate list, tuple, set, and dictionary by syntax and properties
- [ ] I can use list methods: append, insert, extend, pop, remove, sort, reverse
- [ ] I can perform set operations: union, intersection, difference, symmetric difference
- [ ] I can use dictionary methods: get, update, pop, keys, values, items
- [ ] I understand mutability: lists and dicts are mutable; tuples and strings are immutable
- [ ] I can write programs for frequency counting, duplicate removal, and merging dictionaries
- [ ] I know that
sort()returns None (in-place) vssorted()returns a new list - [ ] I can trace through code and predict outputs for collection operations
