Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing elements from an array in python

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.

like image 980
aba Avatar asked Dec 05 '25 19:12

aba


1 Answers

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.

like image 128
Martijn Pieters Avatar answered Dec 08 '25 07:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!