SubodhD SubodhD - 5 months ago 7
Python Question

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?

Answer

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.

Comments