SubodhD
SubodhD

Reputation: 308

Identify the non-zero element in a list which is close to given number in Python

I have list like this:

lst = [1, 5, 0, 0, 4, 0]

EDIT: I would like find the location of the first number in list that is not equal to zero and it is closest given number.

a = 3  # (given number)

It should return 4 as index and value too. I tried with this:

min(enumerate(lst), key=lambda x: abs(x[1]-a))

but its shows the 0 element too.

which is the better way for doing this?

Upvotes: 3

Views: 204

Answers (2)

arachnivore
arachnivore

Reputation: 197

Your answer is pretty close. You just need to replace zero with infinity.

min(enumerate(lst), key=lambda x: abs(a - (x[1] if x[1] else float("inf"))))

Edit: flipped a and x[1]

Upvotes: 2

Ilja Everilä
Ilja Everilä

Reputation: 52929

If I understood you correctly, just filter out the zeros after enumerating:

In [1]: lst = [1, 5, 0, 0, 4, 0]

In [2]: a = 3

In [3]: min(filter(lambda x: x[1] != 0, enumerate(lst)),
            key=lambda x: abs(x[1] - a))
Out[3]: (4, 4)

Your own example does return (4, 4) too for the given values though. With a = 0 there's a difference.

Upvotes: 5

Related Questions