Current Affairs updated daily
KalviGavaniKalviGavani
Class 12 · Tamil Nadu State Board

Samacheer Kalvi 12th Computer Science Chapter 9 Lists Tuples Sets and Dictionaries Exercise Solutions | KalviGavani

Complete TN State Board Class 12 Computer Science Chapter 9 Lists Tuples Sets and Dictionaries exercise solutions — Python list methods (append, insert, pop, remove, sort, reverse), tuple operations, set operations (union, intersection, difference, symmetric_difference), dictionary methods (keys, values, items, get, update, pop) with code examples.

Updated 13 June 202613 min read

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

FeatureListTupleSetDictionary
Syntax[1, 2, 3](1, 2, 3){1, 2, 3}{"a": 1}
OrderedYesYesNo (Python 3.7+ insertion-ordered)Yes (Python 3.7+)
MutableYesNoYesYes
DuplicatesAllowedAllowedNot allowedKeys unique
Indexinglst[0]t[0]No indexingd["key"]
Use caseCollection of itemsFixed collectionUnique itemsKey-value pairs

List Methods

MethodDescriptionExample
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

OperationOperatorMethodExample
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

MethodDescriptionExample
keys()Returns view of all keysd.keys()
values()Returns view of all valuesd.values()
items()Returns view of (key, value) pairsd.items()
get(key)Returns value or Noned.get("a")
get(key, default)Returns value or defaultd.get("x", 0)
update(d2)Merge d2 into dd.update({"c": 3})
pop(key)Remove key and return valued.pop("a")
setdefault(key, val)Set key if missingd.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
Answer(c) Tuple — it cannot be modified after creation.

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]]
Answer(a) The + operator concatenates lists → [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
Answer(b) The & operator performs intersection, giving common elements {2, 3}.

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"
Answer(c) get(key, default) returns the default value 0 when the key is not found.

Q5. Which method adds a single element to the end of a list?

  • (a) insert()
  • (b) extend()
  • (c) append()
  • (d) add()
Answer(c) append() adds one element to the end. extend() adds all elements from an iterable.

Fill in the Blanks

Q1. A ______ is an unordered collection of unique elements.

Answerset

Q2. The ______ method removes and returns the last element from a list.

Answerpop()

Q3. In a dictionary, each entry consists of a ______ and a ______.

Answerkey, value

Q4. The ______ operator is used for symmetric difference of two sets.

Answer^ (caret)

Q5. len({1, 2, 2, 3, 3, 3}) returns ______.

Answer3 (sets store only unique elements: {1, 2, 3})

True or False

Q1. A set can contain duplicate elements.

AnswerFalse — Sets automatically remove duplicates; only unique elements are stored.

Q2. List slicing creates a new list.

AnswerTrue — Slicing returns a shallow copy of the portion.

Q3. A tuple with one element can be created as (5,).

AnswerTrue — The comma is necessary; (5) is just an integer, not a tuple.

Q4. Dictionary keys must be immutable types.

AnswerTrue — Only immutable types like strings, numbers, and tuples can be dictionary keys.

Q5. The sort() method returns a new sorted list.

AnswerFalse — sort() sorts the list in place and returns None. Use sorted() to get a new sorted list.

Match the Following

Column AColumn 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
Answer1-b, 2-d, 3-c, 4-a, 5-e

Short Answer Questions

Q1. Differentiate between list and tuple.

FeatureListTuple
Syntax[1, 2, 3](1, 2, 3)
MutabilityMutable (can change)Immutable (cannot change)
SpeedSlowerFaster
MethodsMany (append, pop, sort...)Few (count, index)
Dictionary keyCannot be a keyCan be a dictionary key
Use whenData changes frequentlyData 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

MistakeWhy It's WrongCorrection
tuple[0] = 5Tuples are immutableConvert to list first or create a new tuple
{1, 2, 3}[0]Sets are unordered, no indexingConvert to list first: list({1,2,3})[0]
lst = lst.sort()sort() returns NoneUse lst.sort() (in place) or sorted(lst) (returns new list)
dict["key"] when key missingRaises KeyErrorUse dict.get("key", default)
(5) as a single-element tupleThis is just the integer 5Use (5,) with a trailing comma
Using mutable objects as dict keysLists/sets cannot be keysUse tuples or strings as keys
Confusing append() and extend()append([1,2]) adds a nested listUse 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) vs sorted() returns a new list
  • [ ] I can trace through code and predict outputs for collection operations

Frequently Asked Questions

A list is mutable (elements can be added, removed, or changed) and uses square brackets []. A tuple is immutable (cannot be modified after creation) and uses parentheses (). Tuples are faster and can be used as dictionary keys.
← Browse all Class 12 Exercise Solutions

Other question types — same chapter