Home > Enterprise >  How can we Check if something other than a value in a list in Python?
How can we Check if something other than a value in a list in Python?

Time:10-22

I want to know if there is a value other than a specific value in a list in python, for example: given a list

lst = [0,0,0,0,0,0,0]

How can I check if there is a value other than 0 in it like 1 or 2 or 3 or any number other than 0 and its position? Example :

lst = [0,0,0,0,1,0,0,0]

The check operation should bring a true value saying yes list have value other than 0, that value and its position as 4.

CodePudding user response:

to get the positions and values of nonzero elements you can do this:

lst = [0,0,0,0,1,0,0,0,2]
list(filter(lambda x: x[1]!=0, enumerate(lst)))  # [(4, 1), (8, 2)]

CodePudding user response:

You can use enumerate to get values plus their index in the list.

lst = [0,0,0,0,1,0,0,0]
baddies = [i for i,val in enumerate(lst)]
has_baddies = bool(baddies)

To short-circuit on the first bad apple a for loop would be a good option

for baddie, val in enumerate(lst):
    if has_baddies := val != 0:
        break
else:
    baddie = None

CodePudding user response:

Using the same output as @SergFSM, this is another tricky option using collections:

lst = [0, 0, 0, 0, 1, 0, 0, 0, 2]
print([f"({lst.index(f)}, {f})" for f in dict(collections.Counter(lst)) if f != 0])

['(4, 1)', '(8, 2)']

CodePudding user response:

Use itertools.compress from the standard library. Take advantage that 0 is cast to False:

from itertools import compress

lst = [0,0,0,0,1,0,99, 0,0]

res = list(compress(enumerate(lst), lst))

if res:
    print(*res)
else:
    print('Only 0s.')
  • Related