3

Unless I'm mistaken, a range can only include unique numbers. So, a number could be in it or not.

I guess only if we want to pass a range as one of many accepted types (dynamic) to some function would it make sense.

However, it seems like if it would go over the whole range to count a number it would be very inefficient.

I tried to time it compared to "in", but on my machine it seems they have the same timing. Can that be right?

PascalVKooten
  • 18,070
  • 15
  • 82
  • 140

1 Answers1

7

Because range() objects conform to the Sequence ABC, and that ABC has a .count() method.

In other words, it is there for completeness sake, so that the object qualifies as a sequence.

It doesn't have to go across the whole range as it is easy enough to calculate if the number is part of the sequence, see Why is `1000000000000000 in range(1000000000000001)` so fast?

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
  • Is it possible to see if it is aware that as soon as it finds a match it can stop? It seems to be the case since a similar timing to "in". – PascalVKooten May 18 '15 at 19:05
  • Wow of course, it just has to compare the minimum and maximum...duh... silly question. That answer is very useful: I like range even a lot more. – PascalVKooten May 18 '15 at 19:08
  • For completeness, [Here](https://hg.python.org/cpython/file/3.4/Objects/rangeobject.c#l366) is what CPython calls when you do `in` on a range object. It appears to be O(1) time. And [here](https://hg.python.org/cpython/file/3.4/Objects/rangeobject.c#l557) is `.count`, which just calls the contains function if the argument is an integer or boolean. So it too is O(1) most of the time. – Kevin May 18 '15 at 19:19
  • Whether it has to go across the whole range depends on the searched value. For example `range(10**8).count(0.)` takes a few seconds before it returns `1`. – superb rain Sep 23 '20 at 22:42
  • @superbrain that’s because you passed in a float. See my [answer on how range containment works](https://stackoverflow.com/questions/30081275/why-is-1000000000000000-in-range1000000000000001-so-fast), only integers trigger the fast calculation path. – Martijn Pieters Sep 24 '20 at 00:57