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?

4 Answers 4

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']
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Thanks. I suppose, that filter is much more faster, then my initial variant:)
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)]"
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']

Comments

2

Use itertools.ifilter:

import itertools

my_array = list(itertools.ifilter(lambda x: x != value_to_remove, my_array))

2 Comments

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.
The list is just for ilustration. Maybe the OP can make use of an generator.
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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.