In: Computer Science
(Programming Language: Python)
Complete the function remove number such that given a list of
integers and an integer n, the function removes every instance
of
n from the list. Remember that this function needs to modify the
list, not return a new list.
# DO NOT ADD ANY OTHER IMPORTS from typing import List
def remove_number(lst: List[int], number: int) -> None:
"""
Remove every instance of number in lst. Do this *in-place*, i.e. *modify* the list. Do NOT return a new list.
>>> lst = [1, 2, 3]
>>> remove_number(lst, 3)
>>> lst
[1, 2]
"""
pass
Please find the code below with the comments at every line of the code and also screenshot of the execution.
#this program will return the list after removing the element that has been passed to remove_number(lst, element)
#defining the function remove_number
def remove_number(lst, element):
#iterating through the loop to remove all the occurences of element in the passed list
for iter in range(len(lst) - 1, -1, -1):
#checking the condition that if it matches the given given element
if lst[iter] == element:
#deleting the element from the list
del lst[iter]
#returning the same list(not the new list)
return lst
#initialinzing the list
lst = [1,2,3,3,3,4,4,2,5,3,2,1,0]
#calling the remove_number method to remove 3 from the list
remove_number(lst,3)
#priniting the list lst
print(lst)
Screenshot of the execution:
Another way of execution :
you can execute by commenting return also to check whether its
removing in the same list or new list:
please find the screenshot below for the same after commenting
return from line 12