10

Is there a way to abbreviate a comparison statement in python so that I don't have to write the whole thing out again? For example, instead of :

a=3
if a==3 or a==2:
    print "hello world"

could I do something like: if a==(3 or 2): print "hello world"

I know the above example won't work but is there another way i can achieve the desired effect?

fergusdawson
  • 1,645
  • 3
  • 17
  • 20

3 Answers3

14
if a in (2, 3):
  print "hello world"
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Re your edit: is it preferable to use a tuple instead of a list? – Levon May 16 '12 at 19:57
  • 4
    @Levon: I don't have a strong preference either way, but to my eye a tuple looks slightly more natural here. – NPE May 16 '12 at 19:58
  • ok, thanks .. I know sometimes there are subtle differences, just wanted to make sure I didn't miss anything as I generally use lists for this. – Levon May 16 '12 at 19:59
  • 4
    It's just a matter of style, but there is definitely a general principle that justifies preferring a tuple to a list: use more restricted tools when you can get away with it, and the powerful ones only when they're needed - that way, the reader of the code won't be distracted by thinking of functionality that won't actually be used. Here, use a tuple because you aren't going to use the list-specific functionality of modification in-place. – Karl Knechtel May 16 '12 at 20:01
  • While it's probably unlikely that this would be a case where it matters, tuples are quite a bit faster to create than lists in Python: http://stackoverflow.com/questions/68630/are-tuples-more-efficient-than-lists-in-python – Wilduck May 16 '12 at 20:17
14

Possible solutions, depending on what exactly you want:

  • if a in (2,3)
  • if a in xrange(2, 4)
  • if 2 <= a <= 3
robert
  • 33,242
  • 8
  • 53
  • 74
  • Is there a benefit to using `xrange` instead of `range` in this case? I'm so glad Python 3 did away with `xrange`. – Mark Ransom May 16 '12 at 20:04
  • @MarkRansom In this case it probably doesn't matter. – robert May 16 '12 at 20:07
  • @robert +1but if it doesn't matter it would be best to use range for py3x compatibility. – jamylak May 16 '12 at 21:58
  • 2
    but range has to put a list in memory with all the numbers so `3 in range(9999999999999)` raises an exception but `3 in xrange(9999999999999)` works – m0etaz Nov 28 '18 at 10:32
13

See Python 3.2 Optimizations regarding the reason for the answer below.

a = 3
if a in {2, 3}:
    print('Hello, world!')
Noctis Skytower
  • 21,433
  • 16
  • 79
  • 117