b8ckwith
b8ckwith

Reputation: 95

Is there a better way to write this if-statement?

What is the better way of doing this:

if pattern[0] != [0] or pattern[0] != [0 , 0] or ... so on:
    # do something

Upvotes: 0

Views: 52

Answers (1)

user2555451
user2555451

Reputation:

It seems like you are looking for any:

if any(pattern[0]):

This solution tests if any of the items in pattern[0] are not equal to 0. It works because 0 evaluates to False in Python. Of course, it also assumes that pattern[0] is iterable since you were comparing it to lists originally.

Also, the condition of your if-statement is incorrect regardless of what you are trying to do. It will always be True because pattern[0] will always be either not equal to [0] or not equal to [0, 0]. You should be using and instead of or:

if pattern[0] != [0] and pattern[0] != [0 , 0] and ... so on:

Upvotes: 7

Related Questions