[Tutor] filtering NaN values

Alan Gauld alan.gauld at btinternet.com
Tue Jun 23 00:37:13 CEST 2009


"Elisha Rosensweig" <benshafat at gmail.com> wrote

> I have a list with some values being NaN (after division-by-zero). How 
> can I
> check and remove all the NaN values?

NaN is, so far as I know, a JavaScript only feature. The equivalent thing
in Python would be to avoid having those 'values' in your list in the first 
place
by trapping the divide by zero error while creating your list, or by not
dividing by zero in the first place:

mylist = []
for item in biglist:
     try: value = item/divisor
     except ZeroDivisionError: continue    # ignore if divide by zero
     mylist.append(value)

OR

mylist = [item/divisor for item in biglist if divisor != 0]   # avoids the 
division


If you can't do either of those then we need a bit more information about
how the "NaN"s come about.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/





More information about the Tutor mailing list