5

I have to remove all specific values from array (if any), so i write:

while value_to_remove in my_array:
    my_array.remove(value_to_remove)

Is there more pythonic way to do this, by one command?

RaSergiy
  • 165
  • 6

4 Answers4

8

You can try:

filter (lambda a: a != value_to_remove, my_array)

Example:

>>> my_array = ["abc", "def", "xyz", "abc", "pop", "abc"]
>>> filter (lambda a: a != "abc", my_array)
['def', 'xyz', 'pop']
Aamir
  • 5,324
  • 2
  • 30
  • 47
  • 1
    This seems the best. The only caveat is if he specifically wants to do an in-place edit if the existing list, in which case there's extra allocation being done compared to the loop in his question. – Silas Ray Oct 23 '12 at 14:24
  • Thanks. I suppose, that filter is much more faster, then my initial variant:) – RaSergiy Oct 23 '12 at 14:33
  • `filter+lambda` is exactly how you are _not_ supposed to do things in python. GvR: "filter(P, S) is almost always written clearer as [x for x in S if P(x)]" – georg Oct 23 '12 at 17:01
3
clean_array = [element for element in my_array if value_to_remove != element]

my_array = ('a','b','a','c')
value_to_remove = 'a'
>>> clean_array = [element for element in my_array if value_to_remove != element]
>>> clean_array
['b', 'c']
jvallver
  • 2,230
  • 2
  • 11
  • 20
2

Use itertools.ifilter:

import itertools

my_array = list(itertools.ifilter(lambda x: x != value_to_remove, my_array))
  • 1
    What benefit does going through `ifilter` give you here? If you just push the result back in to a list anyway, a straight `filter` seems better. – Silas Ray Oct 23 '12 at 14:21
  • The list is just for ilustration. Maybe the OP can make use of an generator. –  Oct 23 '12 at 14:24
1

Don't miss that there is an extremely efficient way as follows:

import numpy as Numpy

a = Numpy.array([1,7,3,4,4,6,3,8,7,0,8])
b = Numpy.array(['1','7','3','4','4','6','3','8','7','0','8'])
c = Numpy.array([0.1,9.8,-0.4,0.0,9.8,13.7])
d = Numpy.array(['one','three','five','four','three'])

print a
print a[a!=3]

print b
print b[b!='3']

print c
print c[c!=9.8]

print d
print d[d!='three']

and you get:

>>> 
[1 7 3 4 4 6 3 8 7 0 8]
[1 7 4 4 6 8 7 0 8]
['1' '7' '3' '4' '4' '6' '3' '8' '7' '0' '8']
['1' '7' '4' '4' '6' '8' '7' '0' '8']
[  0.1   9.8  -0.4   0.    9.8  13.7]
[  0.1  -0.4   0.   13.7]
['one' 'three' 'five' 'four' 'three']
['one' 'five' 'four']
Developer
  • 8,258
  • 8
  • 49
  • 58