How to check if a variable is binary in Python


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
            return True

Itried it on the following list:




But it doesn’t work when the variable is not binary.
Any help from your side will be appreciated.

Asked By: Khaled DELLAL



I would turn around your logic.

def is_binary(y):
    for x in y:
        if x not in [0,1]:
             return False
    return True

The root of the problem is that you are returning the result at the first iteration round, because the return statement stops the execution of the function. This also makes your break statement redundant. See for more info.

There are two use cases where your original solution works as expected and that is when the list length is one or the error is in the first item of the list y AND the "wrong" value is in the list [0,1, ...9] e.g. y=[0] or y=[1] or y=[1,0] returns True and y=[3] will return False. However, your solution fails, if y=['three'] or y=[13] or y=[0, 0, 3] because it returns True, though it should be False.

Answered By: riigs
def is_binary(arr):
    for num in arr:
        if num not in [0, 1]:
            return False
    return True

I found several mistakes in your code.

Firstly, your code stops when the return statement is executed. So your loop will only be executed once and return the result of the first element in the list.

Secondly, there are two binary numbers, and countless numbers that aren’t binary. You’re just checking if the numbers are in range(2, 10). When the number is not in that range, take 11 as example, since it is not in range(2, 10), it won’t execute the return False statement.

Therefore, rather to check if the number is in countless un-binary numbers, check if the number is not binary.

Answered By: Yeyang

You can also use a list comprehension with the result of checking if each element is binary, and use all to check that all elements are True.

Edit: as @Jonh Coleman suggested, instead of creating a list first and then applying all, we can take advantage of generators, which will only generate values as requested.

We then only need to generate elements until one of them evaluates False. all will take care of that by shortcircuiting and not continuing to request elements to the generator once one of them evaluates False. That will be both more memory and time efficient.


all(i in [0,1] for i in our_list)

Answered By: Sembei Norimaki
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.