Given a list, and we have to remove all occurrences of a given element from the list in Python.
Example:
Input:
list = [10, 20, 10, 30, 10, 40, 10, 50]
n = 10
Output:
list after removing 10 from the list
list = [20, 30, 40, 50]
Logic:
- Run a while loop from 0th element to last element's index.
- Check the element whether it is equal to the number (which is to be removed) or not.
- If any element of the list is equal to the number (which is to be removed), remove that element from the list.
- To remove the number from the list, use list.remove() method.
- After removing the number/element from the list, decrease the length, because one item is deleted, and then continue the loop to check the next item at same index (because after removing the element – next elements shifts to the previous index.
- If element is not found (i.e. is not removed), then increase the loop counter to check next element.
Example:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer