Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?
The range() function generates a sequence of numbers, starting from the first argument, and ending before the second argument.
The range() function in Python 3 creates a lightweight sequence object that stores only start, stop, and step. It does not store all the numbers in memory. When you use the in operator, Python delegates to the __contains__ method, which performs a direct mathematical check rather than iterating through the sequence.
1000000000000000 in range(1000000000000001)
# Returns True in O(1) timeThe in operator checks if the value falls within the start and stop bounds and satisfies the step condition by verifying that (value - start) % step == 0. This means membership testing is always O(1), regardless of how large the range is or where the value sits within it. There is no iteration or number generation involved, which is why the expression executes instantly.