Open In App

Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

In this article, we will understand the reason for "1000000000000000 in range(1000000000000001)" so fast in Python 3 with code Implementation.

Why is 1000000000000000 in range(1000000000000001) so fast in Python 3?

Reason :

"1000000000000000 in range(1000000000000001)" is fast in Python 3 because Python's range() function generates a range object that doesn't actually store all the values in memory but rather generates them dynamically when needed. So, Python efficiently checks whether the value is in the range without needing to iterate over all the elements.

Below, is the solution with code implementation of Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

As seen from syntax, the range function only needs start, stop, and step values to generate the numbers in the range. It means when we check 1000000000000000 in range(1000000000000001), Python doesn't iterate through each number but it first computes whether 1000000000000000 falls within the range by performing a simple comparison of the start and stop values of the range object, which results in it being a very fast operation.

Therefore, even though the range includes numbers up to 1000000000000000, Python doesn't generate all those numbers, making the operation very efficient.

Illustration

Implementation

import time

#   Using 'in' operator with range()
start_time_range = time.time()
result_range = 1000000000000000 in range(1000000000000001)
end_time_range = time.time()
execution_time_range = end_time_range - start_time_range

# Print results and execution times
print("Using 'in' operator with range():")
print("Result:", result_range)
print("Execution Time:", execution_time_range, "seconds")

# Using direct comparison
start_time_comparison = time.time()
result_comparison = 0 <= 1000000000000000 <= 1000000000000000
end_time_comparison = time.time()
execution_time_comparison = end_time_comparison - start_time_comparison

print("\nUsing direct comparison:")
print("Result:", result_comparison)
print("Execution Time:", execution_time_comparison, "seconds")

Output
Using 'in' operator with range():
Result: True
Execution Time: 4.5299530029296875e-06 seconds

Using direct comparison:
Result: True
Execution Time: 7.152557373046875e-07 seconds
Article Tags :