Working With Lists and Dictionaries: Back Exercise Question / Answer

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Chapter 4

WORKING WITH LISTS AND DICTIONARIES


Back Exercise Question / Answer :-
[1] What will the output of the following statements:

a) list1 = [12,32,65,26,80,10]
list1.sort()
print(list1)
Ans.: [10,12,26,32,65,80]
b) list1 = [12,32,65,26,80,10]
sorted(list1)
print(list1)
Ans.: [12,32,65,26,80,10]
c) list1 = [1,2,3,4,5,6,7,8,9,10]
list1[::-2]
list1[:3] + list1[3:]
Ans.:[10,8,6,4,2]
d) list1 = [1,2,3,4,5]
list1[len(list1)-1]
Ans.: 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])

The output will be: [10,20,30,40,[50,60]]

b) myList.extend([80,90])

The output will be: [10,20,30,40,[50,60],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])
Ans. So the output will be:

1
3

[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)
Ans.: [1,2,3]

(b)

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

(c)

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

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

append() extend()

Append add one extend add


element to a list at multiple elements
a time. to a list at a time.

The multiple If user adds


values can be multiple values in
added using a list form of list as
as a parameter but parameter, it will
append adds them add separate
as a list only. values.

Example Example

l1=[1,2,3] l1=[1,2,3]
l1.append([4,5]) l1.append([4,5])
print(l1) print(l1)
The output will be: The output will
[1,2,3,[4,5]] be: [1,2,3,4,5]

[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

Ans. a) The * operator treated as a replication operator when the list object is referred to with
any numeric value. So here it will replicate the list values. Therefore it returns [6,7,8,9,6,7,8,9]

b) It is shorthand operator and as explain earlier it will also produce the similar result like
question a).

c) It also produce the similar result as the statement is just like similar.

[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

Ans .perc=stRecord[3]
print(perc)
b) Marks in the fifth subject.

Ans.marks_sub5 = stRecord[2][4]

print(marks_sub5)
c) Maximum marks of the student
Ans.marks_max = max(stRecord[2])

print(marks_max)

d) Roll No. of the student

Ans. rno = stRecord[1]

print(rno)

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

Ans. sname = stRecord[0]

print(sname)

[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”))

Ans.So here the output will be – Patna

b) print(stateCapital.keys())

Ans.So the output will be – dict_keys([‘Assam’, ‘Bihar’, ‘Maharashtra’, ‘Rajasthan’])

c) print(stateCapital.values())

Ans .So the output will be – dict_values([‘Guwahati’, ‘Patna’, ‘Mumbai’, ‘Jaipur’])

d) print(stateCapital.items())

Ans. So the output will be – dict_items([(‘Assam’, ‘Guwahati’), (‘Bihar’, ‘Patna’), (‘Maharashtra’,


‘Mumbai’), (‘Rajasthan’, ‘Jaipur’)])

e) print(len(stateCapital))

Ans. The output will be – 4

f) print(“Maharashtra” in stateCapital)
Ans.So the output will be – True

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

Ans.So here the output will be – Guwahati

h) del stateCapital[“Assam”]
print(stateCapital)

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

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

Ans. By using loops

l = []
n = int(input("Enter the no. of elements in the list:"))
cnt=0
for i in range(0,n):
lval=int(input("Enter the value to add in list:"))
l.append(lval)
search_item=int(input("Enter the value to search:"))
for i in range(0,len(l)):
if l[i]==search_item:
cnt+=1
print(search_item, "Found in the list", cnt, " times")
With eval

lval = eval(input("Enter the values for the list:"))


search_item=int(input("Enter the value to search:"))
print(search_item, "Found in the list", lval.count(search_item), " 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.

Ans.lval = eval(input("Enter the values for the list:"))


pl =[]
nl =[]
for i in range(len(lval)):
if lval[i]>0:
pl. append(lval[i])
elif lval[i]<0:
nl.append(lval[i])
print("Original List:", lval)
print("Positive List:", pl)
print("Negative List:", nl)
[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:

max 2 = n

print("Largest 1 : “ , max1)

print("Largest 2 : “ , max2)

Method - II

1st = eval (input("Enter list : "))

sorted_list = sorted(1st)

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.
Ans.import statistics as s
lval = eval(input("Enter the values for the list:"))
m = s.median(lval)
print("The median value is:",m)
l = eval(input("Enter the values:"))
l.sort()
len1 =len(l)
mv = len1//2
if len1%2 ==0:
m1, m2 = mv-1, mv
md = (l[m1]+l[m2])/2
else:
md=l[mv]
print("The median value is:",md)
[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.

Ans. l = eval(input("Enter the values:"))


temp=[]
for i in l:
if i not in temp:
temp.append(i)
l=list(temp)
print("List after removing duplicate elements)
[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.

Ans.l = [1,2,3]
list_value=int(input("Enter the value to insert:"))
p=int(input("Enter the position"))
index = p - 1
l.insert(idx,list_value)
print(l)
[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.

a) Delete By element position

l = [1,2,3]
p=int(input("Enter the position to delete:"))
l.pop(p)
print(l)
b) Delete by value

l = [1,2,3]
value=int(input("Enter the position to delete:"))
l.remove(value)
print(l)
[8] Write a Python program to find the highest 2 values in a dictionary.

d = {11:22,33:46,45:76}
s = sorted(d.values())
print(s[-1],s[-2])
[9] Write a Python program to create a dictionary from a string ‘w3resource’ such that
each individual character mates a key and its index value for fist occurrence males the
corresponding value in the dictionary.
Ans.Expected output : {‘3’: 1, ‘s’: 4, ‘r’: 2, ‘u’: 6, ‘w’: 0, ‘c’: 8, ‘e’: 3, ‘o’: 5}

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.

Ans. 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) " ) )

elif choice == 1:

print("Name\tPhone Number")

for key in phonedict: print(key, phonedict [key]) elif choice == 2:

name = input("Enter Friends Name : " )

phone= input("Enter Phone Number : " )

if 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 phone dict :

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 Based Questions – Do your self .


End……

You might also like