1st PUC Computer Science Chapter 10 Tuples and Dictionaries Notes | Class 11 Python Notes
Based on the NCERT Computer Science Class XI textbook chapter.
📚 Chapter Overview
A tuple is an ordered sequence that can contain elements of different data types. Tuple elements are written inside round brackets and separated by commas. Like strings and lists, tuple elements can be accessed using index values.
A dictionary is a mapping data type in Python in which information is stored as key-value pairs. Keys are used to access the corresponding values.
📑 Table of Contents
- 10.1 Introduction to Tuples
- 10.1.1 Accessing Elements in a Tuple
- 10.1.2 Tuple is Immutable
- 10.2.1 Concatenation
- 10.2.2 Repetition
- 10.2.3 Membership
- 10.2.4 Slicing
- 10.3 Tuple Methods & Built-in Functions
- 10.4 Tuple Assignment
- 10.5 Nested Tuples
- 10.6 Tuple Handling
- 10.7 Introduction to Dictionaries
- 10.7.1 Creating a Dictionary
- 10.7.2 Accessing Items
- 10.8 Dictionaries are Mutable
- 10.9 Dictionary Operations
- 10.10 Traversing a Dictionary
- 10.11 Dictionary Methods & Functions
- 10.12 Manipulating Dictionaries
- Python Programs
- Exercise & Programming Problems
- Case Study-based Questions
- Quick Revision
- Important Questions
10.1 Introduction to Tuples
📌 Meaning of Tuple
Key Points
- Tuple elements are enclosed in round brackets ( ).
- Elements are separated by commas.
- Tuple elements have fixed positions.
- Indexing starts from 0.
- A tuple can contain different data types.
- A tuple can contain a list or another tuple as an element.
tuple1 = (1, 2, 3, 4, 5) print(tuple1)
tuple2 = ('Economics', 87, 'Accountancy', 89.6)
print(tuple2)
tuple3 = (10, 20, 30, [40, 50]) print(tuple3)
tuple4 = (1, 2, 3, 4, 5, (10, 20)) print(tuple4)
📌 Single Element Tuple
If a tuple contains only one element, a comma must follow the element. Without the comma, Python treats the expression as an ordinary value.
Incorrect
tuple5 = (20) print(type(tuple5))
Result: <class 'int'>
Correct
tuple5 = (20,) print(type(tuple5))
Result: <class 'tuple'>
(20,).
Tuple Without Parentheses
seq = 1, 2, 3 print(type(seq)) print(seq)
A comma-separated sequence without parentheses is also treated as a tuple.
10.1.1 Accessing Elements in a Tuple
Tuple elements can be accessed using indexing and slicing, similar to lists and strings.
tuple1 = (2, 4, 6, 8, 10, 12) print(tuple1[0]) print(tuple1[3]) print(tuple1[-1]) print(tuple1[1+4])
IndexError.
10.1.2 Tuple is Immutable
tuple1 = (1, 2, 3, 4, 5) tuple1[4] = 10
An attempt to assign a new value to an existing tuple position results in
a TypeError.
Mutable Element Inside a Tuple
Although the tuple itself is immutable, an element inside it may be a mutable object such as a list.
tuple2 = (1, 2, 3, [8, 9]) tuple2[3][1] = 10 print(tuple2)
Here the list inside the tuple can be modified.
10.2.1 Concatenation
+ operator.
tuple1 = (1, 3, 5, 7, 9) tuple2 = (2, 4, 6, 8, 10) tuple3 = tuple1 + tuple2 print(tuple3)
Output:
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Extending a Tuple
tuple6 = (1, 2, 3, 4, 5) tuple6 = tuple6 + (6,) tuple6 = tuple6 + (7, 8, 9) print(tuple6)
10.2.2 Repetition
* operator repeats
the elements of a tuple.
tuple1 = ('Hello', 'World')
print(tuple1 * 3)
Output:
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
tuple2 = ('Hello',)
print(tuple2 * 4)
Output:
('Hello', 'Hello', 'Hello', 'Hello')
10.2.3 Membership
The in operator checks whether an element is present in a
tuple. It returns True when present and False
otherwise.
tuple1 = ('Red', 'Green', 'Blue')
print('Green' in tuple1)
print('Green' not in tuple1)
Output:
True False
| Operator | Meaning |
|---|---|
in |
Checks whether the element is present. |
not in |
Checks whether the element is absent. |
10.2.4 Slicing
Slicing can be applied to tuples in the same way as strings and lists.
tuple1 = (10, 20, 30, 40, 50, 60, 70, 80)
| Expression | Result | Purpose |
|---|---|---|
tuple1[2:7] |
(30, 40, 50, 60, 70) |
Elements from index 2 up to index 6 |
tuple1[0:len(tuple1)] |
Entire tuple | All elements |
tuple1[:5] |
(10, 20, 30, 40, 50) |
From beginning |
tuple1[2:] |
(30, 40, 50, 60, 70, 80) |
From index 2 to end |
tuple1[0:len(tuple1):2] |
(10, 30, 50, 70) |
Step size 2 |
tuple1[-6:-4] |
(30, 40) |
Negative indexing |
tuple1[::-1] |
(80, 70, 60, 50, 40, 30, 20, 10) |
Reverse order |
10.3 Tuple Methods and Built-in Functions
| Function / Method | Purpose | Example |
|---|---|---|
len() |
Returns the number of elements. | len((10,20,30)) → 3 |
tuple() |
Creates a tuple from a sequence; without an argument it creates an empty tuple. | tuple([1,2,3]) → (1,2,3) |
count() |
Counts occurrences of an element. | (10,20,10).count(10) → 2 |
index() |
Returns the index of the first occurrence. | (10,20,30).index(30) → 2 |
sorted() |
Returns a new sorted list from tuple elements. | sorted((3,1,2)) → [1,2,3] |
min() |
Returns the smallest element. | min((19,12,56)) → 12 |
max() |
Returns the largest element. | max((19,12,56)) → 56 |
sum() |
Returns the sum of numeric elements. | sum((10,20,30)) → 60 |
sorted() returns a new
list; it does not change the original tuple.
10.4 Tuple Assignment
- The number of variables should match the number of values.
- Values are assigned according to their positions.
- Expressions on the right side are evaluated before assignment.
(num1, num2) = (10, 20) print(num1) print(num2)
record = ("Pooja", 40, "CS")
(name, rollNo, subject) = record
print(name)
print(rollNo)
print(subject)
ValueError.
(a, b, c, d) = (5, 6, 8)
Result: Not enough values to unpack.
Assignment with Expressions
(num3, num4) = (10 + 5, 20 + 5)
After evaluation, num3 = 15 and num4 = 25.
10.5 Nested Tuples
Nested tuples can be useful for storing records containing several related values, such as roll number, name and marks of students.
students = (
(101, "Aman", 98),
(102, "Geet", 95),
(103, "Sahil", 87),
(104, "Pawan", 79)
)
print("S_No Roll_No Name Marks")
for i in range(len(students)):
print(i + 1, students[i][0], students[i][1], students[i][2])
| S_No | Roll_No | Name | Marks |
|---|---|---|---|
| 1 | 101 | Aman | 98 |
| 2 | 102 | Geet | 95 |
| 3 | 103 | Sahil | 87 |
| 4 | 104 | Pawan | 79 |
10.6 Tuple Handling
Program: Swapping Two Numbers Without a Temporary Variable
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("\nNumbers before swapping:")
print("First Number:", num1)
print("Second Number:", num2)
(num1, num2) = (num2, num1)
print("\nNumbers after swapping:")
print("First Number:", num1)
print("Second Number:", num2)
\t inserts horizontal tab space and
\n inserts a new line.
Program: Area and Circumference of a Circle Using a Function
def circle(r):
area = 3.14 * r * r
circumference = 2 * 3.14 * r
return (area, circumference)
radius = int(input("Enter radius of circle: "))
area, circumference = circle(radius)
print("Area of circle is:", area)
print("Circumference of circle is:", circumference)
Program: Store n Numbers in a Tuple and Find Maximum & Minimum
numbers = tuple()
n = int(input("How many numbers do you want to enter?: "))
for i in range(n):
num = int(input())
numbers = numbers + (num,)
print("\nThe numbers in the tuple are:")
print(numbers)
print("The maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
10.7 Introduction to Dictionaries
- A key is separated from its value by a colon
:. - Consecutive items are separated by commas.
- Dictionary items are accessed using keys.
- Keys must be unique.
- Keys should be of an immutable type such as number, string or tuple.
- Values can be repeated and can be of different data types.
{key1:value1, key2:value2, ...}
10.7.1 Creating a Dictionary
Empty Dictionary
dict1 = {}
print(dict1)
dict2 = dict()
print(dict2)
Dictionary with Data
dict3 = {
"Mohan":95,
"Ram":89,
"Suhel":92,
"Sangeeta":85
}
print(dict3)
{ } are used for
dictionary creation, and each key-value pair is separated by a colon.
10.7.2 Accessing Items in a Dictionary
Unlike strings, lists and tuples, dictionary items are accessed using their keys rather than relative positions.
dict3 = {
"Mohan":95,
"Ram":89,
"Suhel":92,
"Sangeeta":85
}
print(dict3["Ram"])
print(dict3["Sangeeta"])
Output:
89 85
KeyError.
print(dict3["Shyam"])
Result: KeyError.
10.8 Dictionaries are Mutable
10.8.1 Adding a New Item
dict1 = {
"Mohan":95,
"Ram":89,
"Suhel":92,
"Sangeeta":85
}
dict1["Meena"] = 78
print(dict1)
10.8.2 Modifying an Existing Item
dict1["Suhel"] = 93.5 print(dict1)
10.9 Dictionary Operations
10.9.1 Membership
The in operator checks whether a key is present in a
dictionary.
dict1 = {
"Mohan":95,
"Ram":89,
"Suhel":92,
"Sangeeta":85
}
print("Suhel" in dict1)
print("Suhel" not in dict1)
True False
10.10 Traversing a Dictionary
A dictionary can be traversed using a for loop.
Method 1 – Traverse Keys
dict1 = {
"Mohan":95,
"Ram":89,
"Suhel":92,
"Sangeeta":85
}
for key in dict1:
print(key, ":", dict1[key])
Method 2 – Traverse Key-Value Pairs
for key, value in dict1.items():
print(key, ":", value)
items() is useful when both
key and value are required during traversal.
10.11 Dictionary Methods and Built-in Functions
| Method / Function | Purpose | Typical Use |
|---|---|---|
len() |
Returns number of key-value pairs. | len(dict1) |
dict() |
Creates a dictionary from key-value pairs. | dict(pair1) |
keys() |
Returns the dictionary keys. | dict1.keys() |
values() |
Returns the dictionary values. | dict1.values() |
items() |
Returns key-value pairs. | dict1.items() |
get() |
Returns the value corresponding to a key; returns None if the key is absent. | dict1.get("Sangeeta") |
update() |
Adds key-value pairs from another dictionary. | dict1.update(dict2) |
del |
Deletes a specified item or the complete dictionary. | del dict1["Ram"] |
clear() |
Removes all items from the dictionary. | dict1.clear() |
Important Examples
dict1 = {
"Mohan":95,
"Ram":89,
"Suhel":92,
"Sangeeta":85
}
print(len(dict1))
print(dict1.keys())
print(dict1.values())
print(dict1.items())
print(dict1.get("Sangeeta"))
dict2 = {"Sohan":79, "Geeta":89}
dict1.update(dict2)
del dict1["Ram"]
dict1.clear()
10.12 Manipulating Dictionaries
Dictionary manipulation includes creating, accessing, adding, modifying, searching and deleting key-value pairs.
Dictionary Example – ODD
ODD = {
1:"One",
3:"Three",
5:"Five",
7:"Seven",
9:"Nine"
}
print(ODD.keys())
print(ODD.values())
print(ODD.items())
print(len(ODD))
print(7 in ODD)
print(2 in ODD)
print(ODD.get(9))
del ODD[9]
print(ODD)
💻 Important Python Programs
Program – Employee Names and Salaries
num = int(input("Enter the number of employees: "))
employee = {}
count = 1
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\nEMPLOYEE_NAME\tSALARY")
for key in employee:
print(key, "\t\t", employee[key])
Program – Count Character Occurrences in a String
st = input("Enter a string: ")
dic = {}
for ch in st:
if ch in dic:
dic[ch] += 1
else:
dic[ch] = 1
for key in dic:
print(key, ":", dic[key])
Program – Convert Digits into Number Names
def convert(num):
numberNames = {
0:"Zero", 1:"One", 2:"Two", 3:"Three", 4:"Four",
5:"Five", 6:"Six", 7:"Seven", 8:"Eight", 9:"Nine"
}
result = ""
for ch in num:
key = int(ch)
result = result + " " + numberNames[key]
return result
num = input("Enter any number: ")
result = convert(num)
print("The number is:", num)
print("The numberName is:", result)
🖼️ Educational Visual – Railway Reservation System
The textbook presents a railway reservation system as an example of dividing a complex system into different subsystems. Each subsystem can be modelled using functions.
📝 Exercise & Programming Problems
Tuple Output Questions
-
For
tuple1 = (23,1,45,67,45,9,55,45)andtuple2 = (100,200), find the output of:tuple1.index(45),tuple1.count(45),tuple1 + tuple2,len(tuple2),max(tuple1),min(tuple1),sum(tuple2)andsorted(tuple1).
Dictionary Output Questions
Consider:
stateCapital = {
"AndhraPradesh":"Hyderabad",
"Bihar":"Patna",
"Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"
}
Find the output of:
stateCapital.get("Bihar")stateCapital.keys()stateCapital.values()stateCapital.items()len(stateCapital)"Maharashtra" in stateCapitalstateCapital.get("Assam")del stateCapital["Rajasthan"]followed by printing the dictionary
Conceptual Questions
- Explain why lists and tuples are ordered.
- Show with an example how a function can return more than one value.
- What advantages do tuples have over lists?
- When should a tuple or dictionary be used? Give suitable programming situations.
- Explain how a variable is rebuilt in the case of immutable data types.
- Why does
len(tuple1)produce an error whentuple1 = (5)?
Programming Problems
- Read email IDs of n students and store them in a tuple. Create separate tuples for usernames and domain names.
- Input names of n students into a tuple and check whether a given student is present.
- Write a Python program to find the highest two values in a dictionary.
- Write a Python program to create a dictionary from a string by counting letters.
- Input friends’ names and phone numbers into a dictionary and perform display, add, delete, modify, search and sorted-display operations.
📊 Case Study-based Questions
SMIS Student Records
Design a program using a dictionary where roll number can act as the key and an immutable data type containing student name and percentage can act as the value.
- Accept details of n students.
- Search for a student using roll number.
- Display the results of all students.
- Find the topper.
- Find subject toppers.
Banking System
- Open a savings bank account.
- Deposit money.
- Withdraw money while considering minimum balance.
- Take fixed-deposit amount and period and display maturity amount.
- Use functions and appropriate data types.
Quiz System
- Create an administrative user ID and password.
- Add, modify and delete questions.
- Register students before participation.
- Allow category selection.
- Display questions according to category.
- Maintain and display the score.
Indian Heritage Sites System
Create a system for storing and searching information about Indian World Heritage Sites.
- Site name
- Location
- District and State
- Year built
- Builder
- Purpose
- Website link, if available
Transportation Reservation System
Choose a mode of transportation and design a reservation system. A railway reservation system can be divided into subsystems such as train information, reservation information, staff/security/infrastructure, food service, billing service and other railway details.
❓ Short Questions & Answers
(20,).+ operator.* operator with tuples?in operator do?KeyError.get() do?None if the key is absent.items()?clear() do?📝 Important Questions for Exam
Very Short Answer
- Define tuple.
- What is immutability?
- Write the syntax for a single-element tuple.
- What is tuple concatenation?
- What is tuple repetition?
- What is tuple slicing?
- Define nested tuple.
- Define dictionary.
- What is a key-value pair?
- What is dictionary mutability?
- What is the use of
keys()? - What is the use of
values()? - What is the use of
items()? - What is the use of
get()? - What is the use of
update()?
2-Mark / Short Answer Questions
- Explain why tuples are immutable with an example.
- Differentiate between list and tuple.
- Explain positive and negative indexing in tuples.
- Explain tuple concatenation with an example.
- Explain tuple repetition with an example.
- Explain tuple slicing with examples.
- Explain tuple assignment.
- Explain nested tuples.
- Explain how a tuple can be used to return multiple values from a function.
- Explain how dictionary items are accessed.
- Explain how to add and modify dictionary items.
- Explain dictionary traversal using a
forloop. - Differentiate between
get()and direct dictionary indexing. - Explain
update(),delandclear().
Programming Questions
- Write a program to swap two numbers without using a temporary variable.
- Write a program to calculate area and circumference of a circle using a function returning a tuple.
- Write a program to input n numbers into a tuple and find maximum and minimum.
- Write a program to store employee names and salaries in a dictionary.
- Write a program to count character occurrences in a string using a dictionary.
- Write a function to convert digits into their corresponding number names.
- Write a program to find the highest two values in a dictionary.
- Write a program to create a dictionary from a string.
Difference Between List and Tuple
| List | Tuple |
|---|---|
| Mutable. | Immutable. |
| Elements are commonly stored using square brackets. | Elements are commonly stored using round brackets. |
| Elements can be changed after creation. | Elements cannot be changed after creation. |
| Useful when data may need modification. | Useful when data should remain unchanged. |
Difference Between Tuple and Dictionary
| Tuple | Dictionary |
|---|---|
| Ordered sequence. | Mapping of keys to values. |
| Elements are accessed using indices. | Values are accessed using keys. |
| Tuple is immutable. | Dictionary is mutable. |
| Uses round brackets for representation. | Uses curly braces for representation. |
⚡ Quick Revision
Tuple – Must Remember
- Tuple is an ordered sequence.
- Tuple elements are normally enclosed in round brackets.
- Elements are separated by commas.
- Indexing starts from 0.
- Tuples are immutable.
- A single-element tuple requires a comma.
+performs concatenation.*performs repetition.inandnot inperform membership checking.- Slicing works with tuples.
- Important functions/methods:
len(),tuple(),count(),index(),sorted(),min(),max(),sum(). - Nested tuple means a tuple inside another tuple.
- Tuple assignment can assign several values at once.
Dictionary – Must Remember
- Dictionary is a mapping data type.
- Information is stored as key-value pairs.
- Keys are separated from values using
:. - Keys must be unique.
- Keys act as the index for accessing values.
- Keys should be immutable types.
- Values can be repeated and can be of different data types.
- Dictionaries are mutable.
inchecks dictionary keys.keys()returns keys.values()returns values.items()returns key-value pairs.get()retrieves a value for a key.update()adds key-value pairs from another dictionary.deldeletes an item or dictionary.clear()removes all dictionary items.
📌 Chapter Summary
Tuples are immutable ordered sequences whose elements can be accessed through indexing and slicing. They support operations such as concatenation, repetition and membership checking. Python provides several functions and methods for processing tuples.
Dictionaries store information as key-value pairs. Keys are unique and
are used to access values. Dictionaries are mutable and can be modified
by adding, changing or deleting items. They can also be traversed using
loops and manipulated using methods such as keys(),
values(), items(), get(),
update() and clear().
📝 This article was researched and written by Venkatesh A, Founder of verakworld.com.