3

I have a variable, and want to check if it matches at least one of the other two variables.

Clearly I can do:

if a == b or a == c:

But I want to know if there is any shorter way, something like:

if a == (b or c):

How to test if a variable is the same as - at least - one of the others?

Tim
  • 41,901
  • 18
  • 127
  • 145
Droids
  • 262
  • 1
  • 9
  • You should rephrase the question. Currently it implies you want `if a == b and a == c` – Tim May 07 '14 at 08:28
  • @TimCastelijns: I edited it, hopefully that was what you meant. Also it wasn't me who phrased the question; someone other edited my initial post to the misleading question – Droids May 07 '14 at 12:19
  • I see, it's a shame that other edit got through the review. Thanks for editing – Tim May 07 '14 at 12:22

1 Answers1

13

For that use in:

if a in (b, c):

Testing for membership in a tuple has an average case of O(n) time complexity. If you have a large collection of values and are performing many membership tests on the same collection of values, it may be worth creating a set for speed:

x = set((b,c,d,e,f,g,h,i,j,k,l,...))
if a in x:
    ...
if y in x:
    ...    

Once it has been constructed, testing for membership in the set has an average case of O(1) time complexity, so it is potentially faster in the long run.

Or, you can also do:

if any(a == i for i in (b,c)):
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • Your point about time complexity is invalid as it neglects the cost of constructing the `set` from the tuple, which appears to grow linearly with the length of the tuple. If you are concerned about time, you should use `a in (b, c)`. – Tom Fenech May 06 '14 at 14:48
  • @TomFenech, Oh right! Thank you. Completely missed that. I am updating my answer. – sshashank124 May 06 '14 at 14:49
  • I have reworded the explanation a bit. Feel free to roll it back if you don't like it. – Tom Fenech May 06 '14 at 15:27
  • @TomFenech, You said in a few lines, 100 times more clearly than what I was saying in 20. Thank you so much! – sshashank124 May 06 '14 at 15:28