How do I check if a tuple is only made up of two numbers?

Viewed 319

I'm trying to make a function that makes sure that my tuple is only made up of zeros or ones.

def zero_um(maze):
    for i in range(len(maze)):
        if maze[i]==0 and maze[i]==1:
                return True
            else:
                return False

However this will always lead to false because a numer can't be one and zero at the same time. But if i try:

def zero_um(tpl):
    for i in range(len(tpl)):
        if tpl[i]==0 or tpl[i]==1:
                return True
            else:
                return False

but that accepts asnwers like (1,2) I've also tried with using != but ran into similar dilemas

3 Answers

Iterate over each value in the tuple, and if it is not 0 or 1, return False.

for value in mytuple:
    if value not in [0,1]:
        return False
return True

You can use set(maze) <= {0, 1}.

By the way returning True or False in if branches is never a good idiom since you can just return the expression itself:

return set(maze) <= {0, 1}

instead of

if set(maze) <= {0, 1}:
    return True
else:
    return False

This works:

def zero_um(tpl):
    return all(x in [0, 1] for x in tpl)

x in [0, 1] checks if something is 0 or 1, ... for x in tpl performs this for every element x, and all makes sure they are all true, otherwise it returns false.

Alternatively we can write:

def zero_um(tpl):
    return set(tpl) <= {0, 1}
Related