dd13
dd13

Reputation: 25

Return first n non NaN value in python list

How do you get the first n elements of a list returned that are not nan values?

For example:

lst = [nan, nan, nan, nan, nan, nan, nan, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

n = 3 

Output: [1,2,3]

Thanks.

Upvotes: 0

Views: 520

Answers (1)

Bharel
Bharel

Reputation: 26954

You can do it using itertools.filterfalse() together with math.isnan():

import math, itertools
nan = float("nan")
lst = [nan, nan, nan, nan, nan, nan, nan, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list(itertools.islice(itertools.filterfalse(math.isnan, lst), 3))

Itertools usage is mainly an optimization and can be replaced with normal slicing:

[i for i in lst if not math.isnan(i)][:3]

As @Pranav emphasized in the comments, even if the first approach looks a bit more complicated, it prevents the whole list from being processed and stops as soon as the first 3 non-nan numbers are encountered. It is much more efficient when you have large lists.

Upvotes: 3

Related Questions