Class 11 Informatics Practices Chapter 4 Working with Lists and Dictionaries NCERT Solution

CBSE NCERT Solution of Class 11 Informatics Practices

Chapter 4 – Working with Lists and Dictionaries


1. What will be the output of the following statements?

a) list1 = [12,32,65,26,80,10]
list1.sort()
print(list1)

Answer: [10, 12, 26, 32, 65, 80]

b) list1 = [12,32,65,26,80,10]
sorted(list1)
print(list1)

Answer: [12,32,65,26,80,10]


c) list1 = [1,2,3,4,5,6,7,8,9,10]
list1[ : : -2]
list1[ : 3] + list1[3 : ]

Answer: [10, 8, 6, 4, 2]

d) list1 = [1,2,3,4,5]
list1[len(list1)-1]

Answer: 5


2. Consider the following list myList. What will be the elements of myList after each of the following operations?

myList = [10,20,30,40]
a) myList.append([50,60])
b) myList.extend([80,90])

Answer:
(a) myList = [10, 20, 30, 40, [50, 60] ]

(b) myList = [10, 20, 30, 40, 80, 90 ]

3. What will be the output of the following code segment?

myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len(myList)):
    if i%2 == 0 :
       print(myList[i]) 

Answer: Output:

1

3

5

7

9

4. What will be the output of the following code segment?

a) myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3 : ]
print(myList)

Answer: [1, 2, 3]

b) myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)

Answer: [6, 7, 8, 9, 10]

c) myList = [1,2,3,4,5,6,7,8,9,10]
del myList[: : 2]
print(myList)


Answer: [2, 4, 6, 8, 10]

5. Differentiate between append() and extend() methods of list.

Answer: The append() method adds an item to the end of the list. The append( ) methods takes exactly one element and return no values.

List.append(item)

After append(), the length of the list will increase by 1 element only.

>>> L = [32, 25, 65]

>>> L.append(98)

>>> L

[32, 25, 65, 98]

The extend() method adds multiple items i.e. an another list to the list. The append( ) takes a list as an argument and appends all of the elements of the argument list.

List.extend(list1)

After extend( ), the length of the list will increase by the length of inserted list.

>>> L = [32, 25, 65]

>>> L.extend( [98, 88, 101] )

>>> L

[32, 25, 65, 98, 88, 101]

6. Consider a list: list1 = [6, 7, 8, 9]
What is the difference between the following operations on list1:

a) list1 * 2
b) list1 *= 2
c) list1 = list1 * 2

Answer:

(a) list1 * 2 ; Creates a new list having replication of list1, i.e. [6, 7, 8, 9, 6, 7, 8, 9]

(b) list1 *= 2 ; Replicate the value of list1 two times and assign the same to list1. i.e. value of list1 is [6, 7, 8, 9, 6, 7, 8, 9]

(c) list1 = list1 * 2; Replicate the value of list1 two times and assign the same to list1. i.e. value of list1 is [6, 7, 8, 9, 6, 7, 8, 9]

7. The record of a student (Name, Roll No, Marks in five subjects and percentage of marks) is stored in the following list:

stRecord = [‘Raman’, ‘A-36’, [56, 98, 99, 72, 69], 78.8]


Write Python statements to retrieve the following information from the list stRecord.

a) Percentage of the student
b) Marks in the fifth subject
c) Maximum marks of the student
d) Roll No. of the student
e) Change the name of the student from ‘Raman’ to ‘Raghav’

Answer: (a) Percentage of the student

stRecord[3]


Answer: (b) Marks in the fifth subject

stRecord [2][4]

Answer: (c) Maximum marks of the student

max(stRecord[2])

Answer: (d) Roll No. of the student

stRecord[1]


Answer: (e) Change the name of the student from ‘Raman’ to ‘Raghav’

stRecord[0] = ‘Raghav’

8. Consider the following dictionary stateCapital:
stateCapital = {“Assam”:”Guwahati”, “Bihar”:”Patna”, “Maharashtra”:”Mumbai”, “Rajasthan”:”Jaipur”}


Find the output of the following statements:

a) print(stateCapital.get(“Bihar”))

Answer: Patna

b) print(stateCapital.keys())

Answer: dict_keys([‘Assam’, ‘Bihar’, ‘Maharashtra’, ‘Rajasthan’])

c) print(stateCapital.values())

Answer: dict_values([‘Guwahati’, ‘Patna’, ‘Mumbai’, ‘Jaipur’])

d) print(stateCapital.items())

Answer: dict_items([(‘Assam’, ‘Guwahati’), (‘Bihar’, ‘Patna’), (‘Maharashtra’, ‘Mumbai’), (‘Rajasthan’, ‘Jaipur’)])

e) print(len(stateCapital))

Answer: 4

f) print(“Maharashtra” in stateCapital)

Answer: True

g) print(stateCapital.get(“Assam”))

Answer: Guwahati

h) del stateCapital[“Assam”]

print(stateCapital)

Answer: {‘Bihar’: ‘Patna’, ‘Maharashtra’: ‘Mumbai’, ‘Rajasthan’: ‘Jaipur’}

Programming Problems

1. Write a program to find the number of times an element occurs in the list.

Answer:

 listVal = [5, 6, 8, 5, 9, 11, 6, 5, 18]
 n = int(input("Enter items to search : "))
 count = listVal.count(n)
 print(n , "is available", count, "times")

2. Write a program to read a list of n integers (positive as well as negative). Create two new lists, one having all positive numbers and the other having all negative numbers from the given list. Print all three lists.

Answer:

listVal = eval(input("Enter a list, having positive and negative values : "))   # Like [-6, 14, 25, -36, 47, -9, 3]
positiveList = []
negativeList = []
for n in listVal:
    if n < 0:
       negativeList.append(n)
    else:
       positiveList.append(n)
print("Original List : ", listVal)
print("Positive List : ", positiveList)
print("Negative List : ", negativeList)

3. Write a program to find the largest and the second largest elements in a given list of elements.

Answer: Method – I

number = eval(input("Enter List : "))  # like this [5,10,65,2,15,39,24]

max1 = number[0]
max2 = number[0]
for n in number:
        
      if max1 < n :
            max2 = max1
            max1 =  n
      elif max2 < n:
            max2 = n
  
print("Largest 1 : ", max1)
print("Largest 2 : ", max2)

Method – II

lst  = eval(input("Enter list : "))
sorted_list = sorted(lst)
print("The 1st Largest Element : ", sorted_list[0])
print("The 2nd Largest Element : ", sorted_list[1])

4. Write a program to read a list of n integers and find their median.
Note: The median value of a list of values is the middle one when they are arranged in order. If there are two middle values then take their average.

Hint: Use an inbuilt function to sort the list.

Answer:

lst  = eval(input("Enter list : "))
lst.sort()
length = len(lst)
mid = length // 2
if length % 2 != 0:
   median = lst[mid]
else:
   mid1, mid2 = mid-1, mid
   median = (lst[mid1] + lst[mid2]) // 2

print("The Median Value is ", median)

5. Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements i.e. all elements occurring multiple times in the list should appear only once.

Answer:

lst = eval(input("Enter List : "))
newlist = []
for num in lst:
   if num not in newlist:
      newlist.append(num)
lst = newlist
print("List without duplicate element : ", lst)

6. Write a program to create a list of elements. Input an element from the user that has to be inserted in the list. Also input the position at which it is to be inserted.

Answer:

lst = eval(input("Enter List : "))

newelement = int(input("Enter element to be insert  :"))
position = int(input("Enter valid index position "))

lst.insert( position, newelement )
print("List after insertion : ", lst)

7. Write a program to read elements of a list and do the following.
a) The program should ask for the position of the element to be deleted from the list and delete the element at the desired position in the list.
b) The program should ask for the value of the element to be deleted from the list and delete this value from the list.

Answer:

lst = eval(input("Enter List : "))

position = int(input("Enter valid index position, to delete element "))

lst.pop(position)
print("List after deletion ", lst)

value = int(input("Enter value to be delete  :"))

lst.remove( value )
print("List after removing element : ", lst)

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

Answer:

numdict = {5 : 555, 8:23, 9:254, 3:658, 7:658}
val = sorted(numdict.values(), reverse = True)
print("Highest two values are ", val[0], "and", val[1])

9. Write a Python program to create a dictionary from a string ‘w3resource’ such that each individual character makes a key and its index value for first occurrence makes the corresponding value in dictionary.

Expected output : {‘3’: 1, ‘s’: 4, ‘r’: 2, ‘u’: 6, ‘w’: 0, ‘c’: 8, ‘e’: 3, ‘o’: 5}

Answer:

string = ‘w3resource’
dict = {}
index = 0
for char in string:
    if char not in dict:
       dict[char] = index
    index = index + 1 

print("Dictionary :", dict)

Output is :

Dictionary : {‘w’: 0, ‘3’: 1, ‘r’: 2, ‘e’: 3, ‘s’: 4, ‘o’: 5, ‘u’: 6, ‘c’: 8}

10. Write a program to input your friend’s, 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 for 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:

phonedict = {}
n = int(input("How many friends details want to add : "))
for t in range(n):
    name = input("Enter Friends Name : ")
    phone = input("Enter Phone Number : ")
if name not in phonedict:     
   phonedict[name] = phone
print("Friends Dictionary is : ", phonedict)
while True:
    print("1. Display All Friends")
    print("2. Add Friend ")
    print("3. Delete a friend ")
    print("4. Modify phone number :")
    print("5. Search friend")
    print("6. Sorted on Names")
    print("7. Exit")
    choice = int(input("Enter your choice (1-7)"))
    if choice == 1:
        print("Name\t Phone Number")
        for key in phonedict:
            print(key, phonedict[key])
    elif choice == 2:
        name = input("Enter Friends Name : ")
        phone = input("Enter Phone Number : ")
        if name not in phonedict:
            phonedict[name] = phone
        else:
            print("Name already exists")
    elif choice == 3:
        name = input("Enter Name to delete : ")
        if name in phonedict:
            del phonedict[name]
        else:
            print("No such name exist")
    elif choice == 4:
        name = input("Enter Name to delete : ")
        if name in phonedict:
            phone = input("Enter new phone number : ")
            phonedict[name] = phone
        else:
            print("No such name exist")
    elif choice == 5:
        name = input("Enter Name to Search : ")
        if name in phonedict:
            print(name, "\t", phonedict[name])
        else:
            print("Friend does not exists")
    elif choice == 6:
        keys = sorted(phonedict)
        print("Sorted Phone Directory is ")
        for k in keys:
            print(k, "\t", phonedict[k])
    elif choice == 7:     
        break 
    else:     
        print("invalid choice, please input valid")

Case Study Based Question

For the SMIS System given in Chapter 3, let us do the following:

1. Write a program to take in the roll number, name and percentage of marks for n students of Class X and do the following:
• Accept details of the n students (n is the number of students).
• Search details of a particular student on the basis of roll number and display result.
• Display the result of all the students.
• Find the topper amongst them.
• Find the subject toppers amongst them.
(Hint: Use Dictionary, where the key can be roll number and the value an immutable data type containing name and percentage.)

Case Study

1. A bank is a financial institution which is involved in borrowing and lending of money. With advancement in technology, online banking, also known as internet banking allows customers of a bank to conduct a range of financial transactions through the bank’s website anytime, anywhere. As part of initial investigation you are suggested to:
• Collect a Bank’s application form. After careful analysis of the form, identify the information required for opening a savings account. Also enquire about the rate of interest offered for a savings account.
• The basic two operations performed on an account are Deposit and Withdrawal. Write a menu driven program that accepts either of the two choices of Deposit and Withdrawal, then accepts an amount, performs the transaction and accordingly displays the balance. Remember every bank has a requirement of minimum balance which needs to be taken care of during withdrawal operations. Enquire about the minimum balance required in your bank.
• Collect the interest rates for opening a fixed deposit in various slabs in a savings bank account. Remembers rate may be different for senior citizens.
Finally, write a menu driven program having the following options (use functions and appropriate data types):
• Open a savings bank account
• Deposit money
• Withdraw money
• Take details such as amount and period for a Fixed Deposit and display its maturity amount for a particular customer.

2. Participating in a quiz can be fun as it provides a competitive element. Some educational institutes use it as a tool to measure knowledge level, abilities and/ or skills of their pupils either on a general level or in a specific field of study. Identify and analyse popular quiz shows and write a Python program to create a quiz that should also contain the following functionalities besides the one identified by you as a result of your analysis.
• Create an administrative user ID and password to categorically add or modify delete a question.
• Register the student before allowing her/him to play a quiz.
• Allow selection of category based on subject area.
• Display questions as per the chosen category.
• Keep the score as the participant plays.
• Display final score.

3. Our heritage monuments are our assets. They are a reflection of our rich and glorious past and an inspiration for our future. UNESCO has identified some of Indian heritage sites as World Heritage sites. Collect the following information about these sites:
• What is the name of the site?
• Where is it located?
▪ District
▪ State

• When was it built?
• Who built it?
• Why was it built?
• Website link (if any)
Write a Python program to:
• Create an administrative user ID and password to add, modify or delete an entered heritage site in the list of sites.
• Display the list of world heritage sites in India.
• Search and display information of a world heritage site entered by the user.
• Display the name(s) of world heritage site(s) on the basis of the state input by the user.

Leave a Comment

You cannot copy content of this page

Scroll to Top