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:
use any
made for this
lst = [0,0,0,0,0,1,0]
if any(lst):
print("Value other than 1")
CodePudding user response:
list comprehension and the any()
function:
any([x != 0 for x in lst])
This will check each element x
in lst
and compare if that element x != 0
. It'll return True/False
for each. Then any()
will return True
if everything is True
or False
if any value is False
.
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)