0

For example if I want to write a statement that would return True if 5 equals either one of the integers 1, 3, or 5. How would I write that, except the more direct method of:

if 5 == 1 or 5== 3 or 5== 5:
    return True

I'm asking since the specific expression I want to use this on is rather long.

  • `if 5 in (1,3,5): return True` – inspectorG4dget Jun 12 '17 at 17:39
  • 2
    @inspectorG4dget: In Python 3, `if 5 in {1, 3, 5}:`; use a set where possible. – Martijn Pieters Jun 12 '17 at 17:41
  • @MartijnPieters That's not necessarly a good advice. Have you measured that a set will be faster then a list for small number of elements? Because I doubt it will. – freakish Jun 12 '17 at 17:41
  • @MartijnPieters: is that notation valid in py2x? It's been a while, and OP hasn't tagged the question with a version number. Still, I hadn't thought of using a set - you're probably right that it's faster (though, optimizing to a pre-instantiated frozenset would likely be better) – inspectorG4dget Jun 12 '17 at 17:43
  • @freakish: yes. The set wins hands-down for this specific example (0.4 for 10 million tests vs. 0.87 for the tuple). – Martijn Pieters Jun 12 '17 at 17:43
  • @inspectorG4dget: that's the thing, the Python 3 peephole optimiser stores that set literal as a frozenset constant. – Martijn Pieters Jun 12 '17 at 17:44
  • 1
    @inspectorG4dget: the notation is valid for Python 2.7, but won't be optimised. – Martijn Pieters Jun 12 '17 at 17:44
  • Why. Can't. I. Upvote. A. Comment. More. Than. Once?! I learned something new today – inspectorG4dget Jun 12 '17 at 17:45
  • @freakish: only when matching the very first element does a tuple win in speed (0.33). But that's hardly the average choice, and even with two elements the set already wins for the aggregate case. – Martijn Pieters Jun 12 '17 at 17:46
  • 1
    @inspectorG4dget: [Tuple or list when using 'in' in an 'if' clause?](//stackoverflow.com/a/25368371) – Martijn Pieters Jun 12 '17 at 17:49
  • @freakish At least in Python 3, sets are optimized such that if the number of elements is small enough, a fixed-sized internal table is used rather than a dynamically allocated one, which is probably where the speed comes from, at least in part. – arshajii Jun 12 '17 at 17:53

0 Answers0