Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
range() function generates a sequence of numbers, starting from the first argument, and ending before the second argument. The sequence is generated on-the-fly, which means that the numbers are not actually stored in memory. Instead, the
range() function generates the next number in the sequence only when it is needed, using an algorithm that is designed to be very fast.
In the case of
range() function will generate numbers starting from
0, and ending before
1000000000000001. The number
1000000000000000 is not included in this range, so the
in operator will return
False immediately, without generating any of the other numbers in the range. This is why the expression is fast.
By contrast, if you wrote
1000000000000000 in range(1000000000000001, 10000000000000000), then the
range() function would have to generate all 100 trillion numbers in the range before it could determine that
1000000000000000 is not in the range, which would be much slower.