Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all specific value from array

Tags:

python

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?

like image 767
RaSergiy Avatar asked Oct 23 '12 14:10

RaSergiy


People also ask

How do I remove a specific value from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove all instances of an element from an array?

First Create an empty List of Array. Insert all elements of the array into the list. Remove all those element which is you want to remove using the equals() method. Convert the list back to an array and return it.

How do I remove a specific ID from an array?

To remove an element from an array by ID in JavaScript, use the findIndex() method to find the index of the object with the ID in the array. Then call the splice() method on the array, passing this index and 1 as arguments to remove the object from the array.


2 Answers

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']
like image 147
Aamir Avatar answered Oct 12 '22 00:10

Aamir


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']
like image 31
jvallver Avatar answered Oct 11 '22 23:10

jvallver