Use app×
CLASS 8 FOUNDATION COURSE
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
Join Bloom Tuition
+3 votes
2.6k views
in Computer by (43.0k points)
closed by

NCERT Solutions Class 11, Computer Science, Chapter- 10, Tuples and Dictionaries

To thoroughly grasp this chapter and excel in CBSE exams and competitive tests, utilizing NCERT Solutions is highly recommended. These solutions, crafted by experts in the field, delve into all key concepts covered in the chapter. Specifically designed for the CBSE curriculum, they ensure a comprehensive understanding and invaluable support in your academic endeavors.

In these NCERT Solutions for Class 11 Computer Science, we have discussed all types of NCERT intext questions and exercise questions.

Concepts covered in Class 11 Computer Science chapter- 10 Tuples and Dictionaries, are :

  • Introduction to Tuples
  • Tuple Operations
  • Tuple Methods and Built-in Functions
  • Tuple Assignment
  • Nested Tuples
  • Tuple Handling
  • Introduction to Dictionaries
  • Dictionaries are Mutable
  • Dictionary Operations
  • Traversing a Dictionary
  • Dictionary Methods and Built-in Functions
  • Manipulating Dictionaries

Our NCERT Solutions for Class 11 Computer Science provide detailed explanations to assist students with their homework and assignments. Proper command and ample practice of topic-related questions provided by our NCERT solutions is the most effective way to achieve full marks in your exams. Begin studying right away to ace your exams.

Easily access all solutions and practice questions at your fingertips to kick-start your preparation immediately.

3 Answers

+2 votes
by (43.0k points)
selected by
 
Best answer

NCERT Solutions Class 11, Computer Science, Chapter- 10, Tuples and Dictionaries

Exercise

1. Consider the following tuples, tuple1 and tuple2:

tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)

Find the output of the following statements:

(i) print(tuple1.index(45))

Solution:

The 'index()' function returns the index of the first occurrence of the element in a tuple.

OUTPUT:

(ii) print(tuple1.count(45))

Solution:

The 'count()' function returns the number of times the given element appears in the tuple.

OUTPUT: 3

(iii) print(tuple1 + tuple2)

Solution:

The '+' operator concatenates the two tuples.

OUTPUT:

(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)

(iv) print(len(tuple2))

Solution:

The 'len()' function returns the number of elements in the given tuple.

OUTPUT: 2

(v) print(max(tuple1))

Solution:

The 'max()' function returns the largest element of the tuple.

OUTPUT: 67

(vi) print(min(tuple1))

Solution:

The 'min()' function returns the smallest element of the tuple.
OUTPUT: 1

(vii) print(sum(tuple2))

Solution:

The 'sum()' function returns the sum of all the elements of the tuple.

OUTPUT:
300

(viii) print ( sorted( tuple1 ) )

print(tuple1)

Solution:

The 'sorted()' function takes an element in the tuple and returns a new sorted list. It doesn’t make any changes to the original tuple. Hence, print(tuple1) will print the original tuple1 i.e. (23, 1, 45, 67, 45, 9, 55, 45)

OUTPUT: 
[1, 9, 23, 45, 45, 45, 55, 67]
(23, 1, 45, 67, 45, 9, 55, 45)

2. Consider the following dictionary stateCapital:

stateCapital = {"AndhraPradesh":"Hyderabad", "Bihar":"Patna","Maharashtra":"Mumbai", "Rajasthan":"Jaipur"}

Find the output of the following statements:

(i) print(stateCapital.get("Bihar"))

Solution:

Patna: 'get()' function returns the value corresponding to the key passed as an argument.

(ii) print(stateCapital.keys())

Solution:

dict_keys(['AndhraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan']): 'keys()' function returns the list of the keys in the dictionary.

(iii) print(stateCapital.values())

Solution:

dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur']): 'values()' function returns the list of the values in the dictionary.

(iv) print(stateCapital.items())

Solution:

dict_items([('AndhraPradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra', 'Mumbai'), ('Rajasthan', 'Jaipur')]): 'items()' function returns the list of tuples in key value pair.

(v) print(len(stateCapital))

Solution:

4: 'len()' functions return the length or number of key: value pairs of the dictionary passed as the argument.

(vi) print("Maharashtra" in stateCapital)

Solution:

True: 'in' is a membership operator which returns true if a key is present in the dictionary.

(vii) print(stateCapital.get("Assam"))

Solution:

None: 'get()' function returns 'None' if the key is not present in the dictionary.

(viii) del stateCapital["Rajasthan"] print(stateCapital)

Solution:

del stateCapital["Andhra Pradesh"] will return an error as the key ‘Andhra Pradesh’ is not present in the dictionary. (‘Andhra Pradesh’ and ‘AndhraPradesh’ are different). However, if the key is present it will delete the key: value pair from the dictionary. If the statement is del stateCapital["AndhraPradesh"], print(stateCapital) will then print the remaining key: value pair. {'Bihar': 'Patna', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur'}

3. “Lists and Tuples are ordered”. Explain.

Solution:

In Lists and Tuples, the items are retained in the order in which they are inserted. The elements can always be accessed based on their position. The element at the position or ‘index’ 0 will always be at index 0. Therefore, the Lists and Tuples are said to be ordered collections.

4. With the help of an example show how can you return more than one value from a function.

Solution:

In a tuple, more than one value can be returned from a function by ‘packing’ the values. The tuple can be then ‘unpacked’ into the variables by using the same number of variables on the left-hand side as there are elements in a tuple. 

Example:

Program: 

#Function to compute area and perimeter of the square.
def square(r):
    area = r * r
    perimeter = 4 * r
    #Returns a tuple having two elements area and perimeter, i.e. two variables are packed in a tuple
    return (area, perimeter)
    ​#end of function

side = int(input("Enter the side of the square: "))
#The returned value from the function is unpacked into two variables area and perimeter
area, perimeter = square(side)
print("Area of the square is:",area)
print("The perimeter of the square is:",perimeter)

OUTPUT:
Enter the side of the square: 4
Area of the square is: 16
The perimeter of the square is: 16 

5. What advantages do tuples have over lists?

Solution:

The advantages of tuples over the lists are as follows:

  1. Tuples are faster than lists.

  2. Tuples make the code safe from any accidental modification. If data is needed in a program that is not supposed to be changed, then it is better to put it in ‘tuples’ than in ‘list’.

  3. Tuples can be used as dictionary keys if it contains immutable values like strings, numbers, or other tuples. ‘Lists’ can never be used as dictionary keys as ‘lists’ are mutable.

6. When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.

Solution:

Tuples are used to store the data which is not intended to change during the course of the execution of the program. For example, if the name of months is needed in a program, then the same can be stored in the tuple as generally, the names will either be iterated for a loop or referenced sometimes during the execution of the program.

Dictionary is used to store associative data like the student's roll no. and the student's name. Here, roll no. will act as a key to find the corresponding student's name. The position of the data doesn’t matter as the data can easily be searched by using the corresponding key.

7. Prove with the help of an example that the variable is rebuilt in case of immutable data types.

Solution:

When a variable is assigned to the immutable data type, the value of the variable cannot be changed in place. Therefore, if we assign any other value to the variable, the interpreter creates a new memory location for that value and then points the variable to the new memory location. This is the same process in which we create a new variable. Thus, it can be said that the variable is rebuilt in case of immutable data types on every assignment.

Program to represent the same:

#Define a variable with immutable datatypes as value
var = 50
#Checking the memory location of the variable
print("Before: ",id(var))
#Assign any other value
var = 51
#Checking the memory location of the variable
print("After: ",id(var))

OUTPUT:
Before: 10916064
After: 10916096

It can be seen that the memory location a variable is pointing at after the assignment is different. The variable is entirely new and it can be said that the variable is rebuilt.

+2 votes
by (43.0k points)

8. TypeError occurs while statement 2 is running. Give reason. How can it be corrected?

>>> tuple1 = (5) #statement 1
 >>> len(tuple1) #statement 2

Solution:

The ‘statement 1’ is creating a variable, tuple1 which is of ‘int’ data type. The ‘statement 2’ is checking for the length of the variable, but the argument passed is an ‘int’ data type. The 'len()' function can return the length only when the object is a sequence or a collection. This is the reason for the type error. 

The error can be corrected by adding one comma after ‘5’ in statement 1, as this will create a tuple and as a tuple is a collection, the 'len()' function will not return an error. The correct statement will be:

>>> tuple1 = (5,)
>>> len(tuple1)

1. Write a program to read email IDs of n number of students and store them in a tuple. Create two new tuples, one to store only the usernames from the email IDs and second to store domain names from the email IDs. Print all three tuples at the end of the program.

[Hint: You may use the function split()]

Solution:

#Program to read email id of n number of students. Store these numbers in a tuple.
#Create two new tuples, one to store only the usernames from the email IDs and second to store domain names from the email ids.
emails = tuple()
username = tuple()
domainname = tuple()
#Create empty tuple 'emails', 'username' and domain-name
n = int(input("How many email ids you want to enter?: "))
for i in range(0,n):
    emid = input("> ")
    #It will assign emailid entered by user to tuple 'emails'
    emails = emails +(emid,)
    #This will split the email id into two parts, username and domain and return a list
    spl = emid.split("@")
    #assigning returned list first part to username and second part to domain name
    username = username + (spl[0],)
    domainname = domainname + (spl[1],)

print("\nThe email ids in the tuple are:")
#Printing the list with the email ids
print(emails)

print("\nThe username in the email ids are:")
#Printing the list with the usernames only
print(username)

print("\nThe domain name in the email ids are:")
#Printing the list with the domain names only
print(domainname)

OUTPUT:
How many email ids you want to enter?: 3
> abcde@gmail.com
> test1@meritnation.com
> testing@outlook.com

The email ids in the tuple are:
('abcde@gmail.com', 'test1@meritnation.com', 'testing@outlook.com')

The username in the email ids are:
('abcde', 'test1', 'testing')

The domain name in the email ids are:
('gmail.com', 'meritnation.com', 'outlook.com')

2. Write a program to input names of n students and store them in a tuple. Also, input a name from the user and find if this student is present in the tuple or not. We can accomplish these by:

(a) writing a user defined function

Solution:

#Program to input names of n students and store them in a tuple.
#Input a name from the user and find if this student is present in the tuple or not.
#Using a user-defined function

#Creating user defined function
def searchStudent(tuple1,search):
    for a in tuple1:
        if(a == search):
            print("The name",search,"is present in the tuple")
            return
    print("The name",search,"is not found in the tuple")

name = tuple()
#Create empty tuple 'name' to store the values
n = int(input("How many names do you want to enter?: "))
for i in range(0,n):
    num = input("> ")
    #It will assign emailid entered by user to tuple 'name'
    name = name + (num,)

print("\nThe names entered in the tuple are:")
print(name)

#Asking the user to enter the name of the student to search
search = input("\nEnter the name of the student you want to search? ")
#Calling the search Student function
searchStudent(name,search)

OUTPUT:
How many names do you want to enter?: 3
> Amit
> Sarthak
> Rajesh

The names entered in the tuple are:
('Amit', 'Sarthak', 'Rajesh')

Enter the name of the student you want to search for. Amit
The name Amit is present in the tuple

(b) using the built-in function

Solution:

#Program to input names of n students and store them in a tuple.
#Input a name from the user and find if this student is present in the tuple or not.
#Using a built-in function

name = tuple()
#Create empty tuple 'name' to store the values
n = int(input("How many names do you want to enter?: "))
for i in range(0, n):
    num = input("> ")
    #it will assign emailid entered by user to tuple 'name'
    name = name + (num,)

print("\nThe names entered in the tuple are:")
print(name)

search=input("\nEnter the name of the student you want to search? ")

#Using membership function to check if name is present or not
if search in name:
    print("The name",search,"is present in the tuple")
else:
    print("The name",search,"is not found in the tuple")

OUTPUT:
How many names do you want to enter?: 3
> Amit
> Sarthak
> Rajesh

The names entered in the tuple are:
('Amit', 'Sarthak', 'Rajesh')

Enter the name of the student you want to search for. Animesh
The name Animesh is not present in the tuple

3. Write a Python program to find the highest 2 values in a dictionary.

Solution:

#Write a Python program to find the highest 2 values in a dictionary
#Defining a dictionary
dic = {"A":12,"B":13,"C":9,"D":89,"E":34,"F":17,"G":65,"H":36,"I":25,"J":11}

#Creating an empty list to store all the values of the dictionary
lst = list()

#Looping through each values and storing it in list
for a in dic.values():
    lst.append(a)

#Sorting the list in ascending order, it will store the highest value at the last index
lst.sort()

#Printing the highest and second highest value using negative indexing of the list
print("Highest value:",lst[-1])
print("Second highest value:",lst[-2])

OUTPUT:
Highest value: 89
Second highest value: 65

4. Write a Python program to create a dictionary from a string.

Note: Track the count of the letters from the string.

Sample string : 'w3resource'

Expected output : {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}

Solution:

#Count the number of times a character appears in a given string
st = input("Enter a string: ")

dic = {}
#creates an empty dictionary

for ch in st:
    if ch in dic:
#if next character is already in the dictionary
        dic[ch] += 1
    else:
#if ch appears for the first time
        dic[ch] = 1

#Printing the count of characters in the string
print(dic)

OUTPUT:
Enter a string: meritnation
{'m': 1, 'e': 1, 'r': 1, 'i': 2, 't': 2, 'n': 2, 'a': 1, 'o': 1}
+2 votes
by (43.0k points)

5. Write a program to input your friends’ names and their Phone Numbers and store them in the dictionary as the key-value pair. Perform the following operations on the dictionary:

a) Display the name and phone number of all your friends

b) Add a new key-value pair in this dictionary and display the modified dictionary

c) Delete a particular friend from the dictionary

d) Modify the phone number of an existing friend

e) Check if a friend is present in the dictionary or not

f) Display the dictionary in sorted order of names

Solution:

dic = {}
#Creates an empty dictionary

#While loop to provide the options repeatedly
#it will exit when the user enters 7
while True:
    print("1. Add New Contact")
    print("2. Modify Phone Number of Contact")
    print("3. Delete a Friend's contact")
    print("4. Display all entries")
    print("5. Check if a friend is present or not")
    print("6. Display in sorted order of names")
    print("7. Exit")
    inp = int(input("Enter your choice(1-7): "))

    #Adding a contact
    if(inp == 1):
        name = input("Enter your friend name: ")
        phonenumber = input("Enter your friend's contact number: ")
        dic[name] = phonenumber
        print("Contact Added \n\n")
    #Modifying a contact if the entered name is present in the dictionary
    elif(inp == 2):
        name = input("Enter the name of friend whose number is to be modified: ")
        if(name in dic):
            phonenumber = input("Enter the new contact number: ")        
            dic[name] = phonenumber
            print("Contact Modified\n\n")
        else:
            print("This friend's name is not present in the contact list")
    #Deleting a contact if the entered name is present in the dictionary
    elif(inp == 3):
        name = input("Enter the name of friend whose contact is to be deleted: ")
        if(name in dic):
            del dic[name]
            print("Contact Deleted\n\n")
        else:
            print("This friend's name is not present in the contact list")
    #Displaying all entries in the dictionary
    elif(inp == 4):
        print("All entries in the contact")
        for a in dic:
            print(a,"\t\t",dic[a])
        print("\n\n\n")
    #Searching a friend name in the dictionary
    elif(inp == 5):
        name = input("Enter the name of friend to search: ")
        if(name in dic):
            print("The friend",name,"is present in the list\n\n")
        else:
            print("The friend",name,"is not present in the list\n\n")
    #Displaying the dictionary in the sorted order of the names
    elif(inp == 6):
        print("Name\t\t\tContact Number")
        for i in sorted(dic.keys()):
            print(i,"\t\t\t",dic[i])
        print("\n\n")
    #Exit the while loop if user enters 7
    elif(inp == 7):
        break
    #Displaying the invalid choice when any other values are entered
    else:
        print("Invalid Choice. Please try again\n")

OUTPUT:
1. Add New Contact
2. Modify Phone Number of Contact
3. Delete a Friend's contact
4. Display all entries
5. Check if a friend is present or not
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 1
Enter your friend name: Mohit
Enter your friend's contact number: 98765*****
Contact Added 
 
1. Add New Contact
2. Modify Phone Number of Contact
3. Delete a Friend's contact
4. Display all entries
5. Check if a friend is present or not
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 1
Enter your friend name: Mohan
Enter your friend's contact number: 98764*****
Contact Added 

1. Add New Contact
2. Modify Phone Number of Contact
3. Delete a Friend's contact
4. Display all entries
5. Check if a friend is present or not
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 6
Name Contact Number
Mohan   98764*****
Mohit   98765*****
 
1. Add New Contact
2. Modify Phone Number of Contact
3. Delete a Friend's contact
4. Display all entries
5. Check if a friend is present or not
6. Display in sorted order of names
7. Exit
Enter your choice(1-7): 7

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...