0

What is the better way of doing this:

if pattern[0] != [0] or pattern[0] != [0 , 0] or ... so on:
 # do something
asked Nov 26, 2014 at 1:27
6
  • 1
    Is there a limit, or do you want to detect up to an infinity of zeros? In any case, since pattern[0] can't be both [0] and [0,0] at the same time, you can change the whole thing to if True: :-) Or did you mean and rather than or? Commented Nov 26, 2014 at 1:29
  • well let's say the limit is 20 of zeros [ 0, 0, ->18 more ] Commented Nov 26, 2014 at 1:30
  • what is the else case? Commented Nov 26, 2014 at 1:31
  • @paxdiablo if pattern is [[0, 0]] could it not fit pattern[0] != [0 , 0]? Commented Nov 26, 2014 at 1:32
  • @Brandon, if it is [[0,0]], then pattern[0] != [0] is true. In fact, the whole if statement condition is true regardless of what pattern is set to. That's my point. Commented Nov 26, 2014 at 1:35

1 Answer 1

7

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:
answered Nov 26, 2014 at 1:30
Sign up to request clarification or add additional context in comments.

2 Comments

Until OP clarifies the question re use of and or or, this is technically wrong. It's probably right but you may want to note the discepency in your answer.
@paxdiablo well I need it for OR(as i asked above), but will be nice to have with AND for future reference.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.