Lists, Tuples, and Dictionaries — TN Class 11 CS Exercise Solutions
Complete exercise solutions for the Tamil Nadu Board Class 11 Computer Science chapter Lists, Tuples, and Dictionaries. Covers creation, indexing, slicing, methods, and operations with working Python code.
How to Use This Page
1. Attempt each exercise on your own first — write Python code before looking at solutions. 2. Run every code example in IDLE or a Python editor to verify the output. 3. Practise with different inputs — change list values, dictionary keys, and tuple elements. 4. Understand mutability — lists and dictionaries are mutable; tuples and strings are not. 5. Compare the three data structures — know when to use each one and why.
Key Concepts (Quick Recap)
| Feature | List | Tuple | Dictionary |
|---|
| Syntax | [1, 2, 3] | (1, 2, 3) | {'a': 1, 'b': 2} |
| Ordered | Yes | Yes | Yes (Python 3.7+) |
| Mutable | Yes | No | Yes (values) |
| Indexed | Yes (by position) | Yes (by position) | Yes (by key) |
| Duplicates | Allowed | Allowed | Keys: No, Values: Yes |
| Methods | Many (append, remove, etc.) | Few (count, index) | Many (keys, values, items) |
| Use case | Changeable sequences | Fixed data, dictionary keys | Key-value mappings |
List Operations and Methods:
| Method/Operation | Example | Result | Description |
|---|
| Create | a = [1, 2, 3] | [1, 2, 3] | Create a list |
| Index | a[0] | 1 | Access by position |
| Slice | a[1:3] | [2, 3] | Extract sublist |
| Append | a.append(4) | [1,2,3,4] | Add element at end |
| Insert | a.insert(1, 5) | [1,5,2,3] | Insert at position |
| Extend | a.extend([4,5]) | [1,2,3,4,5] | Add all elements |
| Remove | a.remove(2) | [1,3] | Remove first occurrence |
| Pop | a.pop() | removes last | Remove and return last |
| Pop index | a.pop(1) | removes index 1 | Remove and return at index |
| Sort | a.sort() | sorted list | Sort in place |
| Reverse | a.reverse() | reversed list | Reverse in place |
| Count | a.count(2) | occurrences | Count occurrences |
| Index | a.index(2) | position | Find first index |
| Length | len(a) | integer | Number of elements |
| Membership | 2 in a | True/False | Check if element exists |
| Concatenation | [1,2] + [3,4] | [1,2,3,4] | Join two lists |
| Repetition | [1] * 3 | [1,1,1] | Repeat list |
| Min/Max | min(a), max(a) | values | Smallest/largest |
Tuple Operations:
| Method/Operation | Example | Result | Description |
|---|
| Create | t = (1, 2, 3) | (1, 2, 3) | Create a tuple |
| Single element | t = (5,) | (5,) | Comma is required |
| Index | t[0] | 1 | Access by position |
| Slice | t[1:3] | (2, 3) | Extract sub-tuple |
| Count | t.count(2) | occurrences | Count occurrences |
| Index | t.index(2) | position | Find first index |
| Length | len(t) | integer | Number of elements |
| Concatenation | (1,2) + (3,4) | (1,2,3,4) | Join two tuples |
| Repetition | (1,) * 3 | (1,1,1) | Repeat tuple |
Dictionary Operations:
| Method/Operation | Example | Result | Description |
|---|
| Create | d = {'a': 1} | {'a': 1} | Create dictionary |
| Access | d['a'] | 1 | Access value by key |
| Add/Update | d['b'] = 2 | {'a':1,'b':2} | Add or update |
| Keys | d.keys() | dict_keys(['a']) | All keys |
| Values | d.values() | dict_values([1]) | All values |
| Items | d.items() | dict_items([('a',1)]) | All key-value pairs |
| Get | d.get('a') | 1 | Get value (safe) |
| Get default | d.get('z', 0) | 0 | Get with default |
| Pop | d.pop('a') | removes key | Remove key-value |
| Update | d.update({'b':2}) | merges | Merge dictionaries |
| Del | del d['a'] | removes entry | Delete key-value |
| In | 'a' in d | True | Check if key exists |
I. Choose the Best Answer (MCQs)
Q1. Which data structure uses key-value pairs? (a) List (b) Tuple (c) Dictionary (d) Set
Answer(c) Dictionary
A dictionary stores data as key-value pairs in curly braces. Each key maps to a specific value. Example: student = {'name': 'Ravi', 'age': 16}.
Q2. Which of the following is immutable? (a) List (b) Dictionary (c) Tuple (d) Set
Answer(c) Tuple
Tuples are immutable — their elements cannot be changed, added, or removed after creation. Lists and dictionaries are mutable.
Q3. What is the output of len([1, [2, 3], 4])? (a) 2 (b) 3 (c) 4 (d) 5
Answer(b) 3
The list has 3 elements: 1, [2, 3], and 4. len() counts top-level elements, not nested elements.
Q4. The method used to add an element at the end of a list is: (a) insert() (b) add() (c) append() (d) push()
Answer(c) append()
append() adds a single element to the end of a list. insert() adds at a specific position, and extend() adds multiple elements.
Q5. What happens when you try to modify a tuple element? (a) It gets modified (b) TypeError is raised (c) ValueError is raised (d) It creates a new tuple
Answer(b) TypeError is raised
Since tuples are immutable, attempting to modify an element raises a TypeError: 'tuple' object does not support item assignment.
Q6. In a dictionary, keys must be: (a) Mutable (b) Immutable (c) Of any type (d) Only strings
Answer(b) Immutable
Dictionary keys must be immutable types like strings, numbers, or tuples. Lists and dictionaries cannot be used as keys because they are mutable.
Q7. What does [1, 2, 3] + [4, 5] produce? (a) [1, 2, 3, 4, 5] (b) [5, 7, 3] (c) [1, 2, 3, [4, 5]] (d) Error
Answer(a) [1, 2, 3, 4, 5]
The + operator concatenates two lists, producing a single list with all elements.
II. Fill in the Blanks
1. A list is a mutable, ordered collection of elements enclosed in square brackets. 2. A tuple is an immutable, ordered collection of elements enclosed in parentheses. 3. A dictionary is a collection of key-value pairs enclosed in curly braces. 4. The append() method adds an element at the end of a list. 5. The extend() method adds all elements of an iterable to the end of a list. 6. The insert() method adds an element at a specified position in a list. 7. The remove() method removes the first occurrence of a specified element from a list. 8. The pop() method removes and returns an element at a given index (default: last element). 9. Tuples are immutable — their elements cannot be changed after creation. 10. Dictionary keys must be immutable (e.g., strings, numbers, tuples). 11. The keys() method returns all keys of a dictionary. 12. The values() method returns all values of a dictionary. 13. The items() method returns all key-value pairs of a dictionary as tuples. 14. To create a single-element tuple, you must include a comma after the element: (5,). 15. The get() method of a dictionary returns None (or a default value) if the key is not found, instead of raising an error.
III. True or False (with corrections for false statements)
Q1. Lists are immutable in Python.
Answer
False. Lists are mutable — their elements can be changed, added, or removed after creation. Tuples are immutable.
Q2. A tuple can contain elements of different data types.
Answer
True. Tuples can contain elements of any type: (1, "hello", 3.14, True). They are heterogeneous collections.
Q3. Dictionary keys can be duplicated.
Answer
False. Dictionary keys must be unique. If you assign a value to an existing key, it overwrites the previous value.
d = {'a': 1, 'a': 2}
print(d) # {'a': 2} — the second value overwrites the first
Q4. The sort() method returns a new sorted list.
Answer
False. sort() sorts the list in place and returns None. To get a new sorted list without modifying the original, use the sorted() function.
a = [3, 1, 2]
b = a.sort() # b is None, a is [1, 2, 3]
c = sorted(a) # c is [1, 2, 3], a is unchanged
Q5. The len() function works on lists, tuples, and dictionaries.
Answer
True. len() returns the number of elements in a list or tuple, and the number of key-value pairs in a dictionary.
Q6. (5) and (5,) are the same tuple.
Answer
False. (5) is just an integer in parentheses (Python treats it as 5). (5,) is a single-element tuple. Always include the trailing comma for a single-element tuple.
Q7. Lists can contain other lists as elements.
Answer
True. Lists can contain any data type, including other lists (nested lists). Example: [[1, 2], [3, 4], [5, 6]].
IV. Match the Following
| Column A | Column B |
|---|
| 1. List | (c) Mutable, ordered, [ ] |
| 2. Tuple | (e) Immutable, ordered, ( ) |
| 3. Dictionary | (a) Mutable, key-value, { } |
| 4. append() | (d) Add one element at end |
| 5. extend() | (b) Add all elements of iterable |
| 6. pop() | (f) Remove and return element |
Answer1–c, 2–e, 3–a, 4–d, 5–b, 6–f
| Column A | Column B |
|---|
1. d.keys() | (e) Returns all keys |
2. d.values() | (f) Returns all values |
3. d.items() | (a) Returns (key, value) pairs |
4. d.get('x', 0) | (d) Returns 0 if key not found |
5. d['x'] = 5 | (b) Add or update key-value |
6. del d['x'] | (c) Delete key-value pair |
Answer1–e, 2–f, 3–a, 4–d, 5–b, 6–c
V. Answer Briefly (2-Mark Questions)
Q1. Differentiate between list and tuple.
Answer
| Feature | List | Tuple |
|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutability | Mutable (can change) | Immutable (cannot change) |
| Methods | Many (append, remove, sort) | Few (count, index) |
| Speed | Slower | Faster |
| Memory | More | Less |
| Use as dict key | Cannot be used | Can be used |
| Use case | Data that changes | Fixed data (coordinates, constants) |
Q2. How do you create and access dictionary elements?
# Creating a dictionary
student = {'name': 'Ravi', 'age': 16, 'marks': 95}
# Accessing elements
print(student['name']) # Ravi — using key
print(student.get('age')) # 16 — using get()
print(student.get('grade', 'N/A')) # N/A — default if key not found
# Adding/updating
student['grade'] = 'A' # Add new key-value
student['marks'] = 98 # Update existing value
print(student)
# {'name': 'Ravi', 'age': 16, 'marks': 98, 'grade': 'A'}
Q3. What is the difference between append() and extend()?
Answer
| Feature | append() | extend() |
|---|
| Adds | Single element | All elements of an iterable |
| Argument | Any single value | List, tuple, string, etc. |
a.append([3,4]) | [1, 2, [3, 4]] | — |
a.extend([3,4]) | [1, 2, 3, 4] | — |
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]] — nested list
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4] — flat list
Q4. Write the difference between remove(), pop(), and del.
Answer
| Method | What it does | Returns | Example |
|---|
remove() | Removes first occurrence of value | None | a.remove(3) |
pop() | Removes element at index (default: last) | Removed element | a.pop(1) |
del | Deletes element at index or entire list | None | del a[1] |
a = [10, 20, 30, 20, 40]
a.remove(20) # [10, 30, 20, 40] — removes first 20
val = a.pop(1) # val = 30, a = [10, 20, 40] — removes and returns index 1
del a[0] # [20, 40] — deletes element at index 0
VI. Answer in Detail (5-Mark Questions)
Q1. Explain lists in Python with creation, indexing, slicing, and methods. Write a program to find the largest and smallest element in a list.
Answer
List Creation:
# Different ways to create lists
numbers = [10, 20, 30, 40, 50] # List of integers
names = ["Ravi", "Priya", "Kumar"] # List of strings
mixed = [1, "hello", 3.14, True] # List of mixed types
nested = [[1, 2], [3, 4], [5, 6]] # Nested list (list of lists)
empty = [] # Empty list
from_range = list(range(1, 6)) # [1, 2, 3, 4, 5]
List Indexing and Slicing:
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# Indexing
print(fruits[0]) # "apple" — first element
print(fruits[-1]) # "elderberry" — last element
print(fruits[2]) # "cherry" — third element
# Slicing
print(fruits[1:4]) # ["banana", "cherry", "date"]
print(fruits[:3]) # ["apple", "banana", "cherry"]
print(fruits[2:]) # ["cherry", "date", "elderberry"]
print(fruits[::-1]) # Reverse: ["elderberry", "date", "cherry", "banana", "apple"]
List Methods:
# Adding elements
a = [10, 20, 30]
a.append(40) # [10, 20, 30, 40] — add at end
a.insert(1, 15) # [10, 15, 20, 30, 40] — add at index 1
a.extend([50, 60]) # [10, 15, 20, 30, 40, 50, 60] — add multiple
# Removing elements
a.remove(15) # [10, 20, 30, 40, 50, 60] — remove value 15
val = a.pop() # val = 60, a = [10, 20, 30, 40, 50] — remove last
val = a.pop(1) # val = 20, a = [10, 30, 40, 50] — remove at index
# Other methods
a.sort() # [10, 30, 40, 50] — sort in ascending order
a.reverse() # [50, 40, 30, 10] — reverse the list
print(a.count(10)) # 1 — count occurrences
print(a.index(40)) # 1 — first index of value
print(len(a)) # 4 — number of elements
Program: Find largest and smallest element in a list
# Program to find largest and smallest in a list
numbers = []
n = int(input("Enter number of elements: "))
for i in range(n):
num = int(input(f"Enter element {i+1}: "))
numbers.append(num)
print("List:", numbers)
print("Largest element:", max(numbers))
print("Smallest element:", min(numbers))
# Without using max() and min():
largest = numbers[0]
smallest = numbers[0]
for num in numbers:
if num > largest:
largest = num
if num < smallest:
smallest = num
print("Largest (manual):", largest)
print("Smallest (manual):", smallest)
Output:
Enter number of elements: 5
Enter element 1: 34
Enter element 2: 12
Enter element 3: 89
Enter element 4: 5
Enter element 5: 67
List: [34, 12, 89, 5, 67]
Largest element: 89
Smallest element: 5
Largest (manual): 89
Smallest (manual): 5
Q2. Explain dictionaries in Python with creation, access, methods, and operations. Write a program to count the frequency of each character in a string using a dictionary.
Answer
Dictionary Creation:
# Different ways to create dictionaries
student = {'name': 'Ravi', 'age': 16, 'marks': 95}
empty = {} # Empty dictionary
from_pairs = dict([('a', 1), ('b', 2)]) # From list of tuples
from_kwargs = dict(name='Priya', age=17) # From keyword arguments
# Accessing values
print(student['name']) # Ravi — using key
print(student.get('age')) # 16 — using get()
print(student.get('grade', 'N/A')) # N/A — default value
# Modifying dictionary
student['grade'] = 'A' # Add new key-value pair
student['marks'] = 98 # Update existing value
student['age'] += 1 # Modify value
print(student)
# {'name': 'Ravi', 'age': 17, 'marks': 98, 'grade': 'A'}
Dictionary Methods:
student = {'name': 'Ravi', 'age': 16, 'marks': 95}
# keys(), values(), items()
print(student.keys()) # dict_keys(['name', 'age', 'marks'])
print(student.values()) # dict_values(['Ravi', 16, 95])
print(student.items()) # dict_items([('name', 'Ravi'), ('age', 16), ('marks', 95)])
# Iterating through dictionary
for key in student:
print(key, ":", student[key])
# Using items() for key-value pairs
for key, value in student.items():
print(f"{key} = {value}")
# pop() — remove and return value
marks = student.pop('marks') # marks = 95, 'marks' key removed
# update() — merge dictionaries
student.update({'school': 'ABC', 'city': 'Chennai'})
# Checking if key exists
if 'name' in student:
print("Name exists:", student['name'])
# delete a key
del student['age']
Dictionary Operations:
# Length
d = {'a': 1, 'b': 2, 'c': 3}
print(len(d)) # 3
# Membership (checks keys, not values)
print('a' in d) # True
print(1 in d) # False (1 is a value, not a key)
print(1 in d.values()) # True (check values)
# Copy a dictionary
d2 = d.copy()
# Clear all entries
d.clear() # d becomes {}
Program: Count character frequency using a dictionary
# Program to count frequency of each character in a string
def char_frequency(text):
freq = {}
for char in text:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
return freq
# Main program
string = input("Enter a string: ")
result = char_frequency(string)
print("\nCharacter Frequency:")
print("-" * 25)
for char, count in sorted(result.items()):
print(f"'{char}' : {count}")
# Total characters
print(f"\nTotal characters: {len(string)}")
print(f"Unique characters: {len(result)}")
Output:
Enter a string: programming
Character Frequency:
-------------------------
'g' : 2
'i' : 1
'm' : 2
'n' : 1
'o' : 1
'p' : 1
'r' : 2
'a' : 1
Total characters: 11
Unique characters: 8
Trace for "programming": p→1, r→1, o→1, g→1, r→2, a→1, m→1, m→2, i→1, n→1, g→2
Q3. Explain tuples in Python with creation, operations, and methods. Write a program to: (a) Swap two numbers using tuples (b) Create a student record using a dictionary and display it.
Answer
Tuple Creation:
# Different ways to create tuples
t1 = (1, 2, 3, 4, 5) # Tuple of integers
t2 = ("apple", "banana") # Tuple of strings
t3 = (1, "hello", 3.14, True) # Mixed types
t4 = () # Empty tuple
t5 = (5,) # Single element (comma required!)
t6 = tuple([1, 2, 3]) # From a list
t7 = tuple("abc") # From a string: ('a', 'b', 'c')
# Important: (5) is an integer, NOT a tuple
print(type((5))) # <class 'int'>
print(type((5,))) # <class 'tuple'>
Tuple Indexing and Slicing:
t = (10, 20, 30, 40, 50)
# Indexing
print(t[0]) # 10 — first element
print(t[-1]) # 50 — last element
# Slicing
print(t[1:4]) # (20, 30, 40)
print(t[:3]) # (10, 20, 30)
print(t[::-1]) # (50, 40, 30, 20, 10) — reversed
Tuple Operations:
# Concatenation
t1 = (1, 2, 3)
t2 = (4, 5, 6)
print(t1 + t2) # (1, 2, 3, 4, 5, 6)
# Repetition
print(t1 * 3) # (1, 2, 3, 1, 2, 3, 1, 2, 3)
# Membership
print(2 in t1) # True
# Length
print(len(t1)) # 3
# Min, Max
print(min(t1)) # 1
print(max(t1)) # 3
Tuple Methods:
t = (1, 2, 3, 2, 4, 2)
# count() — number of occurrences
print(t.count(2)) # 3
# index() — first index of value
print(t.index(2)) # 1
# Sorted (returns a list, not tuple)
print(sorted(t)) # [1, 2, 2, 2, 3, 4]
print(tuple(sorted(t))) # (1, 2, 2, 2, 3, 4)
Why use tuples?
- Immutable — data cannot be accidentally changed
- Faster than lists (no modification overhead)
- Can be used as dictionary keys (lists cannot)
- Used for fixed data like days of week, coordinates, constants
(a) Program: Swap two numbers using tuples
# Program to swap two numbers using tuple packing/unpacking
a = int(input("Enter first number (a): "))
b = int(input("Enter second number (b): "))
print(f"Before swapping: a = {a}, b = {b}")
# Swap using tuple packing and unpacking
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")
Output:
Enter first number (a): 10
Enter second number (b): 20
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10
How it works: b, a creates a tuple (20, 10). Then a, b = (20, 10) unpacks the tuple, assigning 20 to a and 10 to b.
(b) Program: Student record using a dictionary
# Program to create and display a student record using a dictionary
# Create student dictionary
student = {}
# Input student details
student['roll_no'] = int(input("Enter roll number: "))
student['name'] = input("Enter name: ")
student['class'] = input("Enter class: ")
student['marks'] = {}
# Input marks for 3 subjects
subjects = ['Tamil', 'English', 'Maths']
for subject in subjects:
mark = int(input(f"Enter {subject} marks: "))
student['marks'][subject] = mark
# Calculate total and average
total = sum(student['marks'].values())
average = total / len(student['marks'])
student['total'] = total
student['average'] = average
# Determine grade
if average >= 90:
student['grade'] = 'A'
elif average >= 80:
student['grade'] = 'B'
elif average >= 70:
student['grade'] = 'C'
elif average >= 60:
student['grade'] = 'D'
else:
student['grade'] = 'E'
# Display student record
print("\n" + "=" * 40)
print(" STUDENT RECORD")
print("=" * 40)
print(f"Roll Number : {student['roll_no']}")
print(f"Name : {student['name']}")
print(f"Class : {student['class']}")
print("-" * 40)
print("Subject-wise Marks:")
for subject, mark in student['marks'].items():
print(f" {subject:10s} : {mark}")
print("-" * 40)
print(f"Total : {student['total']}")
print(f"Average : {student['average']:.2f}")
print(f"Grade : {student['grade']}")
print("=" * 40)
Output:
Enter roll number: 101
Enter name: Ravi
Enter class: 11
Enter Tamil marks: 92
Enter English marks: 85
Enter Maths marks: 98
========================================
STUDENT RECORD
========================================
Roll Number : 101
Name : Ravi
Class : 11
----------------------------------------
Subject-wise Marks:
Tamil : 92
English : 85
Maths : 98
----------------------------------------
Total : 275
Average : 91.67
Grade : A
========================================
Common Mistakes to Avoid
1. Creating a single-element tuple without a comma — (5) is an integer, not a tuple. Always write (5,) for a single-element tuple.
2. Trying to modify a tuple — t[0] = 10 raises TypeError. Tuples are immutable. Convert to a list first if you need to modify: lst = list(t).
3. Confusing append() and extend() — append([3,4]) adds a nested list; extend([3,4]) adds individual elements.
4. Using a list as a dictionary key — Dictionary keys must be immutable. Use tuples or strings as keys, not lists.
5. Accessing a dictionary key that doesn't exist — d['x'] raises KeyError if 'x' is not in the dictionary. Use d.get('x', default) for safe access.
6. Confusing sort() and sorted() — list.sort() sorts in place and returns None. sorted(list) returns a new sorted list without modifying the original.
7. Forgetting that pop() returns a value — val = lst.pop() removes the last element AND returns it. If you don't store it, the value is lost.
8. Using del vs remove() incorrectly — del lst[1] removes by index; lst.remove(value) removes by value. They are not interchangeable.
Exam Checklist
Before your exam, make sure you can:
- [ ] Create lists, tuples, and dictionaries with proper syntax
- [ ] Access elements by index (positive and negative)
- [ ] Slice lists and tuples with start, end, and step
- [ ] Use all list methods (append, insert, extend, remove, pop, sort, reverse, count, index)
- [ ] Use tuple methods (count, index) and understand immutability
- [ ] Create, access, and modify dictionaries
- [ ] Use dictionary methods (keys, values, items, get, pop, update)
- [ ] Differentiate between mutable (list, dict) and immutable (tuple, str) types
- [ ] Write programs: find max/min in list, count frequency, swap values, student records
- [ ] Use
len(), min(), max(), sum() with lists and tuples - [ ] Iterate through lists, tuples, and dictionaries using for loops
- [ ] Explain when to use list vs tuple vs dictionary