Current Affairs updated daily
KalviGavaniKalviGavani

CBSE Class 11 Computer Science Chapter 10 Notes: Tuples and Dictionaries

Complete NCERT-aligned guide for CBSE Class 11 Computer Science Chapter 10 — Tuples and Dictionaries covering tuple creation, methods, immutability, dictionary creation, methods, operations, nesting, and iteration with exam tips and revision notes.

Updated 11 June 202615 min read

Exercise Solutions Available

Step-by-step answers for all textbook questions in this chapter

View Solutions →

CBSE Class 11 Computer Science Chapter 10 — Tuples and Dictionaries

Chapter Introduction

After learning about lists in Chapter 9, this chapter introduces two more essential Python data structures: tuples and dictionaries. A tuple is like a list but immutable — once created, its contents cannot be changed. This makes tuples ideal for data that should remain constant, such as coordinates, RGB colour values, or database records. A dictionary is a completely different structure: it stores data as key-value pairs, letting you look up any value instantly by its key. Dictionaries are the backbone of JSON data, configuration settings, and fast data retrieval in Python.

This chapter covers tuple creation, methods, immutability, dictionary creation, methods, operations, nesting, and practical programs. Mastering both is critical for the CBSE Class 11 Computer Science exam.


Key Definitions

TermDefinition
TupleAn ordered, immutable sequence of items enclosed in parentheses ().
ImmutabilityThe property of a data type that prevents its contents from being changed after creation.
Tuple UnpackingAssigning the elements of a tuple to individual variables in a single statement.
DictionaryAn unordered collection of key-value pairs enclosed in curly braces {}.
KeyA unique, immutable identifier used to access a value in a dictionary.
ValueThe data associated with a key in a dictionary. Can be any type.
Key-Value PairA pair consisting of a key and its associated value, written as key: value.
Nested DictionaryA dictionary that contains another dictionary as one of its values.
get() methodReturns the value for a key if it exists, otherwise returns a default (None) without raising an error.

Detailed Concepts

Part A: TUPLES


1. Creating Tuples

Using parentheses (the standard way):

numbers = (1, 2, 3, 4, 5)
colors = ("red", "green", "blue")
mixed = (1, "hello", 3.14, True)

Without parentheses (tuple packing):

coordinates = 10, 20, 30
print(type(coordinates))  # <class 'tuple'>
print(coordinates)         # (10, 20, 30)

Single-element tuple — the comma is required:

# Correct — comma makes it a tuple
single = (5,)
print(type(single))  # <class 'tuple'>

# Wrong — this is just an integer in parentheses
not_a_tuple = (5)
print(type(not_a_tuple))  # <class 'int'>

Empty tuple:

empty = ()
print(type(empty))  # <class 'tuple'>
print(len(empty))   # 0

Nested tuple:

nested = ((1, 2), (3, 4), (5, 6))
print(nested[0])       # (1, 2)
print(nested[1][0])   # 3

Tuple from a list or string using tuple():

# From a list
nums = tuple([1, 2, 3, 4])
print(nums)  # (1, 2, 3, 4)

# From a string
chars = tuple("Python")
print(chars)  # ('P', 'y', 't', 'h', 'o', 'n')

# From a range
r = tuple(range(1, 6))
print(r)  # (1, 2, 3, 4, 5)

2. Accessing Tuple Elements

Tuples support the same indexing and slicing as lists.

Positive indexing:

t = (10, 20, 30, 40, 50)
print(t[0])   # 10
print(t[3])   # 40

Negative indexing:

t = (10, 20, 30, 40, 50)
print(t[-1])  # 50
print(t[-3])  # 30

Slicing:

t = (10, 20, 30, 40, 50)
print(t[1:4])    # (20, 30, 40)
print(t[:3])     # (10, 20, 30)
print(t[2:])     # (30, 40, 50)
print(t[::-1])   # (50, 40, 30, 20, 10)
print(t[::2])    # (10, 30, 50)

3. Tuple Immutability

Once a tuple is created, you cannot change, add, or remove its elements. Any attempt to modify a tuple raises a TypeError.

t = (1, 2, 3, 4, 5)
# t[0] = 10     # TypeError: 'tuple' object does not support item assignment
# t.append(6)   # AttributeError: 'tuple' object has no attribute 'append'
# del t[2]      # TypeError: 'tuple' object doesn't support item deletion

Workaround — convert to list, modify, convert back:

t = (1, 2, 3, 4, 5)
temp = list(t)
temp[2] = 99
t = tuple(temp)
print(t)  # (1, 2, 99, 4, 5)

However, if a tuple contains a mutable element (like a list), that inner element can be modified:

t = (1, [2, 3], 4)
t[1][0] = 99
print(t)  # (1, [99, 3], 4)  — the inner list is modified

4. Tuple Operations

Concatenation (+):

a = (1, 2, 3)
b = (4, 5, 6)
c = a + b
print(c)  # (1, 2, 3, 4, 5, 6)

*Repetition ():**

a = (1, 2)
print(a * 3)  # (1, 2, 1, 2, 1, 2)

Membership (in / not in):

t = ("apple", "banana", "cherry")
print("banana" in t)      # True
print("mango" not in t)   # True

5. Tuple Methods

Tuples have only two methods (because they are immutable, methods that modify are not available):

MethodSyntaxDescriptionExample
count()tuple.count(item)Returns the number of times an item appears(1,2,1,3).count(1) -> 2
index()tuple.index(item)Returns the index of the first occurrence(1,2,3,2).index(2) -> 1
t = (10, 20, 30, 20, 40, 20)
print(t.count(20))  # 3
print(t.index(20))  # 1  (first occurrence)

# index() with start and end parameters
print(t.index(20, 2))  # 3  (search starts from index 2)

6. Tuple Functions

Built-in functions that work with tuples:

t = (3, 1, 4, 1, 5, 9, 2, 6)

print(len(t))    # 8
print(min(t))    # 1
print(max(t))    # 9
print(sum(t))    # 31
print(sorted(t)) # [1, 1, 2, 3, 4, 5, 6, 9] — returns a LIST

# sorted() with reverse
print(sorted(t, reverse=True))  # [9, 6, 5, 4, 3, 2, 1, 1]

# tuple() to convert back
sorted_tuple = tuple(sorted(t))
print(sorted_tuple)  # (1, 1, 2, 3, 4, 5, 6, 9)

7. Tuple Unpacking

Tuple unpacking assigns each element of a tuple to a separate variable:

# Basic unpacking
point = (3, 7)
x, y = point
print(x)  # 3
print(y)  # 7

# With more elements
info = ("Alice", 17, "Class 11")
name, age, cls = info
print(name)  # Alice
print(age)   # 17
print(cls)   # Class 11

# Using * to capture remaining elements
first, *rest = (1, 2, 3, 4, 5)
print(first)  # 1
print(rest)   # [2, 3, 4, 5]

# Swapping two variables without a temporary variable
a, b = 10, 20
a, b = b, a
print(a)  # 20
print(b)  # 10

Part B: DICTIONARIES


1. Creating Dictionaries

Using curly braces (literal):

student = {
    "name": "Rahul",
    "age": 17,
    "class": "11",
    "marks": 92
}
print(student)  # {'name': 'Rahul', 'age': 17, 'class': '11', 'marks': 92}

Using the dict() constructor:

# From keyword arguments
student = dict(name="Priya", age=16, marks=88)
print(student)  # {'name': 'Priya', 'age': 16, 'marks': 88}

# From a list of tuples
data = dict([("name", "Amit"), ("age", 17), ("city", "Delhi")])
print(data)  # {'name': 'Amit', 'age': 17, 'city': 'Delhi'}

Creating a dictionary from two lists using zip():

keys = ["name", "age", "city"]
values = ["Sneha", 16, "Chennai"]
student = dict(zip(keys, values))
print(student)  # {'name': 'Sneha', 'age': 16, 'city': 'Chennai'}

Empty dictionary:

empty = {}
print(type(empty))  # <class 'dict'>

# Or using dict()
empty2 = dict()

2. Accessing Values

Using key notation (square brackets):

student = {"name": "Rahul", "age": 17, "marks": 92}
print(student["name"])   # Rahul
print(student["age"])    # 17
# print(student["grade"])  # KeyError: 'grade' — key does not exist

Using the get() method:

student = {"name": "Rahul", "age": 17, "marks": 92}
print(student.get("name"))       # Rahul
print(student.get("grade"))      # None  (no error)
print(student.get("grade", "N/A"))  # N/A  (custom default)

Key difference: Square brackets raise a KeyError if the key is missing. get() returns None (or a custom default) instead. Use get() when you are unsure whether the key exists.


3. Dictionary Methods

MethodSyntaxDescriptionExample
keys()dict.keys()Returns a view of all keysd.keys()
values()dict.values()Returns a view of all valuesd.values()
items()dict.items()Returns a view of all (key, value) pairsd.items()
get()dict.get(key, default)Returns value for key; default if missingd.get("x", 0)
update()dict.update(other)Merges key-value pairs from another dictd.update({"x": 1})
pop()dict.pop(key)Removes key and returns its valued.pop("age")
popitem()dict.popitem()Removes and returns last (key, value) paird.popitem()
clear()dict.clear()Removes all itemsd.clear()
setdefault()dict.setdefault(key, default)Returns value if key exists; sets default if notd.setdefault("x", 0)
fromkeys()dict.fromkeys(seq, val)Creates dict from a sequence with same valuedict.fromkeys(["a","b"], 0)

Code examples:

student = {"name": "Rahul", "age": 17, "marks": 92}

# keys(), values(), items()
print(list(student.keys()))    # ['name', 'age', 'marks']
print(list(student.values()))  # ['Rahul', 17, 92]
print(list(student.items()))   # [('name', 'Rahul'), ('age', 17), ('marks', 92)]

# update()
student.update({"city": "Delhi", "marks": 95})
print(student)  # {'name': 'Rahul', 'age': 17, 'marks': 95, 'city': 'Delhi'}

# pop()
age = student.pop("age")
print(age)      # 17
print(student)  # {'name': 'Rahul', 'marks': 95, 'city': 'Delhi'}

# setdefault()
grade = student.setdefault("grade", "A")
print(grade)    # A  (added because "grade" was missing)
print(student)  # {'name': 'Rahul', 'marks': 95, 'city': 'Delhi', 'grade': 'A'}

# fromkeys()
keys = ["math", "science", "english"]
marks = dict.fromkeys(keys, 0)
print(marks)  # {'math': 0, 'science': 0, 'english': 0}

4. Dictionary Operations

Membership test (checks keys only):

student = {"name": "Rahul", "age": 17}
print("name" in student)      # True
print("Rahul" in student)     # False  (checks keys, not values)
print("age" not in student)   # False

Length:

student = {"name": "Rahul", "age": 17, "marks": 92}
print(len(student))  # 3

Iteration:

student = {"name": "Rahul", "age": 17, "marks": 92}

# Iterate over keys
for key in student:
    print(key, "->", student[key])

# Iterate over key-value pairs
for key, value in student.items():
    print(f"{key}: {value}")

5. Modifying Dictionaries

Adding a new key-value pair:

student = {"name": "Rahul", "age": 17}
student["city"] = "Delhi"
print(student)  # {'name': 'Rahul', 'age': 17, 'city': 'Delhi'}

Updating an existing value:

student = {"name": "Rahul", "age": 17, "marks": 88}
student["marks"] = 95
print(student)  # {'name': 'Rahul', 'age': 17, 'marks': 95}

Deleting a key-value pair:

student = {"name": "Rahul", "age": 17, "marks": 92}
del student["age"]
print(student)  # {'name': 'Rahul', 'marks': 92}

# Using pop()
marks = student.pop("marks")
print(marks)    # 92
print(student)  # {'name': 'Rahul'}

6. Nested Dictionaries

A dictionary can contain another dictionary as a value:

students = {
    "student1": {"name": "Rahul", "age": 17, "marks": 92},
    "student2": {"name": "Priya", "age": 16, "marks": 88},
    "student3": {"name": "Amit", "age": 17, "marks": 95}
}

# Access nested values
print(students["student1"]["name"])   # Rahul
print(students["student2"]["marks"]) # 88

# Iterate over nested dictionary
for key, info in students.items():
    print(f"{key}: {info['name']} scored {info['marks']}")
# student1: Rahul scored 92
# student2: Priya scored 88
# student3: Amit scored 95

7. Traversing a Dictionary

Iterating over keys:

student = {"name": "Rahul", "age": 17, "marks": 92}
for key in student:
    print(key)
# name
# age
# marks

Iterating over values:

for value in student.values():
    print(value)
# Rahul
# 17
# 92

Iterating over key-value pairs:

for key, value in student.items():
    print(f"{key} = {value}")
# name = Rahul
# age = 17
# marks = 92

Using enumerate() with items:

for i, (key, value) in enumerate(student.items()):
    print(f"{i}. {key}: {value}")
# 0. name: Rahul
# 1. age: 17
# 2. marks: 92

8. Common Dictionary Programs

Word frequency counter:

text = "the cat sat on the mat the cat ate the rat"
words = text.split()
freq = {}
for word in words:
    freq[word] = freq.get(word, 0) + 1
print(freq)
# {'the': 4, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1, 'ate': 1, 'rat': 1}

Merge two dictionaries:

dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

# Method 1: update()
merged = dict1.copy()
merged.update(dict2)
print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Method 2: unpacking (Python 3.5+)
merged2 = {**dict1, **dict2}
print(merged2)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Invert a dictionary (swap keys and values):

original = {"a": 1, "b": 2, "c": 3}
inverted = {value: key for key, value in original.items()}
print(inverted)  # {1: 'a', 2: 'b', 3: 'c'}

Find the key with the maximum value:

scores = {"Rahul": 92, "Priya": 88, "Amit": 95}
topper = max(scores, key=scores.get)
print(topper)  # Amit

9. Comparison: List vs Tuple vs Dictionary

FeatureListTupleDictionary
Syntax[](){} with key: value
OrderedYesYesYes (Python 3.7+)
MutableYesNoYes
DuplicatesAllowedAllowedKeys: No; Values: Yes
IndexingBy positionBy positionBy key
Use caseDynamic collectionsFixed, constant dataKey-based lookup
Methods11 methods2 methods10 methods
SpeedSlower than tupleFaster than listFast key lookup (O(1))
HashableNoYes (if all elements are hashable)No
MemoryMoreLessMore (overhead per key-value)

Common Mistakes

1. Forgetting the comma in a single-element tuple: (5) is an integer, not a tuple. Write (5,) instead.

2. Trying to modify a tuple: t[0] = 10 raises a TypeError. Convert to a list first if modification is needed.

3. Using a list as a dictionary key: Dictionary keys must be immutable. Using a list as a key raises a TypeError. Use a tuple instead.

4. Assuming in checks dictionary values: The in operator checks keys, not values. Use value in dict.values() to check for a value.

5. Modifying a dictionary while iterating: Adding or deleting keys during iteration can cause runtime errors or skipped items. Iterate over a list of keys instead.

6. Confusing pop() and popitem(): pop(key) removes a specific key and returns its value. popitem() removes and returns the last inserted (key, value) pair as a tuple.

7. Assuming dictionary order before Python 3.7: In Python versions before 3.7, dictionaries did not guarantee insertion order. For CBSE exams using Python 3.7+, insertion order is preserved.

8. Using sorted() on a dictionary: sorted(dict) returns a sorted list of keys, not a sorted dictionary. Use sorted(dict.items()) to get sorted key-value pairs.


Exam Tips

1. Know the immutability distinction thoroughly: Be able to explain why tuples are immutable, what errors occur when you try to modify them, and the workaround of converting to a list.

2. Master the single-element tuple syntax: This is a very common trick question. (5) is an int; (5,) is a tuple.

3. Understand get() vs square bracket access for dictionaries: Know that dict["key"] raises KeyError but dict.get("key") returns None. The exam may ask which is safer and why.

4. Practice dictionary iteration patterns: Be comfortable iterating over keys, values, and items. Know the output format of items() — it returns tuples.

5. Know which types can be dictionary keys: Only immutable (hashable) types — strings, numbers, tuples (containing only immutable types). Lists and other dictionaries cannot be keys.

6. Remember setdefault() behavior: It returns the existing value if the key is present, or sets and returns the default value if the key is absent. This appears in board exams.

7. Practice zip() for creating dictionaries: The pattern dict(zip(keys, values)) is commonly asked. Know how to create a dictionary from two parallel lists.

8. Trace dictionary operations step by step: Many exam questions show a sequence of update(), pop(), and assignment operations. Carefully track the dictionary state after each step.


Quick Revision Notes

  • A tuple is an ordered, immutable sequence. Created with () or comma-separated values.
  • Single-element tuple requires a trailing comma: (5,).
  • Tuples support indexing, slicing, concatenation, and repetition — same as lists.
  • Tuples have only two methods: count() and index().
  • Built-in functions len(), min(), max(), sum(), sorted() all work on tuples.
  • sorted() returns a list, not a tuple. Use tuple(sorted(t)) to get a sorted tuple.
  • Tuple unpacking: a, b, c = (1, 2, 3).
  • A dictionary stores key-value pairs. Created with {} or dict().
  • Dictionary keys must be unique and immutable (strings, numbers, tuples).
  • Access values: dict["key"] (raises KeyError if missing) or dict.get("key") (returns None if missing).
  • keys(), values(), items() return view objects, not lists. Wrap in list() if needed.
  • update() merges another dictionary; existing keys are overwritten.
  • pop(key) removes and returns the value; popitem() removes and returns the last pair.
  • setdefault(key, default) returns value if key exists, otherwise sets and returns default.
  • fromkeys(seq, val) creates a dictionary with all keys from seq set to val.
  • Create dictionary from two lists: dict(zip(keys, values)).
  • in operator checks keys in a dictionary, not values.
  • Nested dictionaries are accessed with chained keys: data["student1"]["name"].
  • Tuples are faster than lists because immutability allows optimisation.

Frequently Asked Questions

Tuples are immutable (cannot be changed after creation) and use parentheses (). Lists are mutable and use square brackets []. Tuples are faster and used for fixed data; lists for dynamic data.