Q.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]
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The function search_replace() takes a list of numbers and a target number; if the target is found, every occurrence is replaced with 0, otherwise a message is displayed.
Let’s think about what this problem is really asking. You have a list — say [10, 20, 30, 10, 40] — and you want to check whether a particular number (like 10) appears anywhere inside it. If it does, you replace every occurrence of that number with 0. If it doesn’t appear at all, you simply print a message saying so.
This is a classic linear search task, but with a twist: instead of stopping at the first match, you must keep scanning the entire list to find and replace all matches. The NCERT Class 11 Computer Science textbook (Chapter on Lists) emphasises that lists are mutable — meaning you can change individual elements by their index. That’s the key idea here.
How do we build this function?
First, you need to know whether the number exists at all. The simplest way is to use the in operator: if n in L: returns True if n is present. But that only tells you if it exists, not where. To actually replace, you need to loop through the list using indices.
Here’s the logic step by step:
- Accept two parameters: the list
Land the number to search, saynum. - Use a
forloop withrange(len(L))so you can access each index. - At each index, check if
L[i] == num. If yes, setL[i] = 0. - Keep a flag (like a boolean variable
found) to track whether any replacement happened. - After the loop, if the flag is still
False, print a message like"Number not found".
You must modify the original list in place, not create a new list. The problem statement shows L = [0,20,30,0,40] — that’s the same list object, just changed. NCERT emphasises that list methods like append() modify the list directly; here we do the same via index assignment.
Why not use list.index()?
The index() method only returns the first occurrence. You’d have to call it repeatedly in a loop, which is messy. A simple for loop over indices is cleaner and matches the NCERT approach for traversing lists.
What about the message when the number is not found?
The problem says “an appropriate message is displayed.” That means you print something like "10 not found in list" — but only if no replacement happened. So the flag is essential. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.