Consider the array a= [1, 2, 3, 1, 2, 3]. Now suppose I want to remove all the 2s in this array in python. So I apply a.remove(2). However the result which comes out is [1, 3, 1, 2, 3], i.e the only first 2 is removed. How can I remove all the 2s which appear in an array? In general, given an array and an element p, how can I remove all the elements of the array which are equal to p?
Edit:- I think I should mention this, this question has been inspired from a Brilliant computer science problem.
Use a list comprehension to build a replacement list, where all elements are not equal to p:
a = [i for i in a if i != p]
Note that in Python, the datatype is called a list, not an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With