range() in Python 2 versus range() in Python 3

We run same Python code in two different Ipython/Jupyter notebooks. The code is designed to highlight the differences in how Python 2 and Python 3 do range(). The function foo, iterates through range(n), but quits the loop the first time the body of the loop is executed. So the body of the loop takes very very little time to execute. So long execution times for foo(n) are mostly the execution time of range(n).


In [1]:
n = 10**7

In [2]:
def foo(n):
    for i in range(n):
        break

In [3]:
foo(n)

In [4]:
%timeit foo(n)


The slowest run took 7.97 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 780 ns per loop

In [5]:
n = 10**8

In [6]:
%timeit foo(n)


The slowest run took 8.00 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 785 ns per loop

In [7]:
n = 10**9

In [8]:
%timeit foo(n)


The slowest run took 8.22 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 782 ns per loop

In [9]:
n = 10**12345

In [10]:
%timeit foo(n)


10000 loops, best of 3: 45.2 µs per loop