Is it worth caching Python's range(start, stop, step)?

It won't, a range call does almost nothing. Only the itering part, which is not optional, has a cost.

Interestingly, caching makes it slower for some reason, in the example below.

My benchmarks:

>>> timeit.timeit("""
for i in range(10000):
    pass""",number=10000)
1.7728144999991855
>>> timeit.timeit("""
for i in r:
    pass""","r=range(10000)",number=10000)
1.80037959999936

And caching it breaks readability, as the Zen of Python states:

Readability counts.

and

Explicit is better than implicit.
Simple is better than complex.

Tags:

Python