Earlier quoted context omitted.
To be pedantic (which I think is warranted here), range does not return a generator, it returns a sequence called a range object. This object can be indexed, sliced, and (relevant to this discussion) supports the 'in' operator. "x in range(10)" will operate in constant time and memory in Python 3. Whether it is actually more efficient than "0 $ python3 -m timeit -s 'x = 8' 'x in range(10)' 1000000 loops, best of 3: 0…
I'm certain that the call to range is significant there, but if you think of how this actually plays out, it may be doing a naive list compare. if a compare operation is your limiting operation, then the former has to do nine operations (Is x == 0? Is x == 1? ... Is x == 8?) vs precisely two in the latter (is x >= 0? Is x From a formal CS perspective, that's why this is wrong; It's because 'in' is an o(n) operation,…
python3 -m timeit -s 'x = 8' 'x in range(1000)'
1000000 loops, best of 3: 0.405 usec per loop
python3 -m timeit -s 'x = 8' '0
While 0<=x<10 seems to be 5 times faster, both seem to be independent of the actual chosen values.