In order to check if a given list is constituted only by 0 and 1 values, I tried to set up a function returning True when the list is binary, while it returns False when not:
My code
def is_binary(y):
for x in y:
if x in [2,3,4,5,6,7,8,9]:
return False
break
else:
return True
Itried it on the following list:
our_list=[1,0,0,0,1,1,0,0,0,0,1,0,1,0,1,1,1]
is_binary(our_list)
Output:
True
But it doesn't work when the variable is not binary. Any help from your side will be appreciated.
return Trueoutside the for loop. Also, wouldn't checking ifx not in [0, 1]be much more intuitive and clear?all(x in {0,1} for x in our_list)not in [0, 1]for the edge case where you have alistwith something other thanints.return all(x in [0,1] for x in y).set(our_list) <= {0, 1}