0

When I am using python for scripting I usually think in the pythonic way of everything. I have recently notice that I can do

if a == 0 or b == 0 or c == 0: # something happens

that way

if 0 in [a,b,c]: # something happens

This way is much more generic and I could dynamically fulfil the list with the items that I need to compare.

There exists a pythonic way for this case?

if a == 0 and b == 0 and c == 0: # something happens

In both case, comparing with 0 it's just an example. It could be something like this

if a == "foo" and b == "foo" and c == "foo": # something happens

And I need a pythonic way for that.

Answer

I leave my answer at the description because I can't reopen the question to post my answer. The pythonic way for that case requires the all() function.

if all(v == 0 for v in (a,b,c)): #something happens
Luis González
  • 3,199
  • 26
  • 43
  • `if 0 in {a, b, c}:` on Python 3, or `if 0 in (a, b, c):` in Python 2 (but the list form is automatically converted to a tuple anyway). – Martijn Pieters Jan 12 '16 at 12:02
  • But your question is too broad, because you made this about *two different cases*. And a duplicate, because the `value in set/tuple` test has been discussed before. – Martijn Pieters Jan 12 '16 at 12:03
  • I would only need an answer for the case: `if a == 0 and b == 0 and c == 0: `. In this case is not necessary that all the elements were compared with 0. It could be something like this: `if a == 1 and b == 2 and c == 3: `. – Luis González Jan 12 '16 at 12:09
  • Have you noticed that the `and` operator is present in the case that generates me doubts ? The first case is set of conditions joined by the `or` operator. The second one is with the `and` operator. Please, pay more attention at the questions and you will avoid to be afraid – Luis González Jan 12 '16 at 12:17
  • @MartijnPieters could you explain why this question is a duplicate? I have seen the other questions, and it's a discussion about the first case (which I already know, and that is what I say in the first two lines ) – Luis González Jan 12 '16 at 12:19
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/100470/discussion-between-luis-gonzalez-and-martijn-pieters). – Luis González Jan 12 '16 at 12:44

0 Answers0