What makes the “1000000000000000 in range(1000000000000001)” so fast in Python 3?


In Python 3, the range() function generates a sequence of numbers on the fly, rather than creating a list of all the numbers in the sequence upfront. This means that when you use the in operator to check if a number is in the range, Python only has to generate the numbers in the range up to the number you're checking, rather than generating the entire range.

For example, when you run the following code:

1000000000000000 in range(1000000000000001)
Python will only generate the numbers in the range up to 1000000000000000, which is much faster than generating the entire range of 1000000000000001 numbers. This is why the code runs so quickly.

It's worth noting that this behavior is specific to Python 3. In Python 2, the range() function creates a list of all the numbers in the range upfront, so checking if a number is in the range is slower, especially for large ranges.

Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.


Subscribe to be the first to know when a new Python course is released.