removing all instances of a certain value from a list

L

Lee Sander

Hi,
I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are
many missing vlaues which are represented as None. I would like to
remove all such instances in one go.
There is a remove function but it removes only the first instance, is
there a delete/remove all function?
thanks
 
B

BJörn Lindqvist

Hi,
I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are
many missing vlaues which are represented as None. I would like to
remove all such instances in one go.
There is a remove function but it removes only the first instance, is
there a delete/remove all function?
thanks

If it is ok to copy the list instead of mutating it, use a list comprehension:
L = [-1.3, 1.22, 9.2, None, 2.3]
[x for x in L if x is not None]
[-1.3, 1.22, 9.1999999999999993, 2.2999999999999998]
 
H

Hrvoje Niksic

Lee Sander said:
Hi,
I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are
many missing vlaues which are represented as None. I would like to
remove all such instances in one go.
There is a remove function but it removes only the first instance, is
there a delete/remove all function?

No, but you can easily simulate it using, for example:

lst[:] = (el for el in lst if el is not None)
 
R

r.grimm

Hi,
I have a float array ( eg [-1.3, 1.22, 9.2, None, 2.3] ) but there are
many missing vlaues which are represented as None. I would like to
remove all such instances in one go.
There is a remove function but it removes only the first instance, is
there a delete/remove all function?
thanks
You can also do it with the filter function.
a= [-1.3, 1.22, 9.2, None, 2.3]
a=filter ( lambda b: b != None, a)
print a
[-1.3, 1.22, 9.1999999999999993, 2.2999999999999998]

Greetings Rainer
 
B

bearophileHUGS

(e-mail address removed):
With None it's better to use is/not is instead of ==/!=

Bye,
bearophile
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top