Test Index

Python Revision Tour Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 102 of 102
Marks: +1, -0
Write a function search_replace() in Python which accepts a list L of numbers and a number to be searched. If the number exists, it is replaced by 0 and if the number does not exist, an appropriate message is displayed.
Example :
L = [10,20,30,10,40]
Number to be searched = 10
List after replacement :
L = [0,20,30,0,40]
[CBSE 2023 Compartment]
Solution:  
def search_replace(L, SN):
found = False
for i in range(len(L)):
if L[i] == SN:
L[i] = 0
found = True
if found == False:
print("Number not found")
else:
print("List after replacement :", L)
L = [10, 20, 30, 10, 40]
SN = int(input("Number to be searched = "))
search_replace(L, SN)
Explanation: The function receives the list and the number. The loop visits every index; wherever the element equals the number, it is replaced by 0 and the flag found is set. After the loop, if the flag is still False the message "Number not found" is displayed. For L = [10,20,30,10,40] and 10, both 10s are replaced and L becomes [0, 20, 30, 0, 40].
© examsnet.com
Advertisements
Go to Question: