NCERT Solutions for Class 11 Science Computer science Chapter 10 – Tuples And Dictionaries
Page No 223:
Question 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:
- print(tuple1.index(45))
- print(tuple1.count(45))
- print(tuple1 + tuple2)
- print(len(tuple2))
- print(max(tuple1))
- print(min(tuple1))
- print(sum(tuple2))
- print(sorted (tuple1))
print(tuple1)
ANSWER:
i. The ‘index()’ function returns the index of the first occurrence of the element in a tuple.
OUTPUT:
2
ii. The ‘count()’ function returns the numbers of times the given element appears in the tuple.
OUTPUT:
3
iii. ‘+’ operator concatenate the two tuples.
OUTPUT:
(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
iv. The ‘len()’ function returns the number of elements in the given tuple.
OUTPUT:
2
v. The ‘max()’ function returns the largest element of the tuple.
OUTPUT:
67
vi. The ‘min()’ function returns the smallest element of the tuple.
OUTPUT:
1
vii. The ‘sum()’ function returns the sum of all the elements of the tuple.
OUTPUT:
300
viii. The ‘sorted()’ function takes element in the tuple and return 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)
Page No 224:
Question 2:
Consider the following dictionary stateCapital:
stateCapital = {“AndhraPradesh”:”Hyderabad”,”Bihar”:”Patna”,”Maharashtra”:”Mumbai”, “Rajasthan”:”Jaipur”}
Find the output of the following statements:
- print(stateCapital.get(“Bihar”))
- print(stateCapital.keys())
- print(stateCapital.values())
- print(stateCapital.items())
- print(len(stateCapital))
- print(“Maharashtra” in stateCapital)
- print(stateCapital.get(“Assam”))
- del stateCapital[“Andhra Pradesh”]
print(stateCapital)
ANSWER:
- Patna: ‘get()‘ function returns the value corresponding to the key passed as an argument.
- dict_keys([‘AndhraPradesh’, ‘Bihar’, ‘Maharashtra’, ‘Rajasthan’]): ‘keys()’ function returns the list of the keys in the dictionary.
- dict_values([‘Hyderabad’, ‘Patna’, ‘Mumbai’, ‘Jaipur’]): ‘values()’ function returns the list of the values in the dictionary.
- dict_items([(‘AndhraPradesh’, ‘Hyderabad’), (‘Bihar’, ‘Patna’), (‘Maharashtra’, ‘Mumbai’), (‘Rajasthan’, ‘Jaipur’)]): ‘items()’ function returns the list of tuples in key value pair.
- 4: ‘len()’ functions return the length or number of key:value pairs of the dictionary passed as the argument.
- True: ‘in’ is a membership operator which returns true if a key is present in the dictionary.
- None: ‘get()’ function returns ‘None’ if the key is not present in the dictionary.
- 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’}
Page No 224:
Question 3:
“Lists and Tuples are ordered”. Explain.
ANSWER:
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.
Page No 224:
Question 4:
With the help of an example show how can you return more than one value from a function.
ANSWER:
In 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
Page No 224:
Question 5:
What advantages do tuples have over lists?
ANSWER:
The advantages of tuples over the lists are as follows:
- Tuples are faster than lists.
- Tuples make the code safe from any accidental modification. If a data is needed in a program which is not supposed to be changed, then it is better to put it in ‘tuples’ than in ‘list’.
- Tuples can be used as dictionary keys if it contains immutable values like strings, numbers or another tuple. ‘Lists’ can never be used as dictionary keys as ‘lists’ are mutable.
Page No 224:
Question 6:
When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.
ANSWER:
Tuples are used to store the data which is not intended to change during the course of 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 student’s roll no. and the student’s name. Here, the 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.
Page No 224:
Question 7:
Prove with the help of an example that the variable is rebuilt in case of immutable data types.
ANSWER:
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 after the assignment is different. The variable is entirely new and it can be said that the variable is rebuilt.
Page No 224:
Question 8:
TypeError occurs while statement 2 is running. Give reason. How can it be corrected?
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2
ANSWER:
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, ‘len()‘ function will not return an error. The correct statement will be:
>>> tuple1 = (5,)
>>> len(tuple1)
Page No 224:
Question 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()]
ANSWER:
Program:
#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’)
Page No 224:
Question 2:
Write a program to input names of n students and store them in a tuple. Also, input 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
(b) using the built-in function
ANSWER:
a) Program:
#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? Amit
The name Amit is present in the tuple
b) Program:
#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? Animesh
The name Animesh is not present in the tuple
Page No 225:
Question 3:
Write a Python program to find the highest 2 values in a dictionary.
ANSWER:
Program:
#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
Page No 225:
Question 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}
ANSWER:
Program:
#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}
Page No 225:
Question 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
ANSWER:
Program:
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