Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I cache range results if I reuse them?

I'm relatively new to python, and I'm trying to optimize some code for a HackerRank problem. I found it odd that using range (i.e. generating a list?) is faster than just using a while loop with a single variable to iterate.

I'm wondering if it's faster to cache the result of the range function if I iterate over the same sequence later in the code. For example:


Is this faster:

ten = 10
zeroToTen = range(ten)

sum = 0
for x in zeroToTen:
    sum += x

product = 1
for y in zeroToTen:
    product *= y

Or should I just recall range each time:

ten = 10

sum = 0
for x in range(10):
    sum += x

product = 1
for y in range(10):
    product *= y
like image 726
Joshua Dawson Avatar asked Mar 10 '23 19:03

Joshua Dawson


2 Answers

In python 3, range is a generator. It means that it will yield all the numbers of the sequence. It's simple additions.

You could cache that in a list: cache = list(range(10)) but that would allocate some memory and would need to iterate on it: not productive!

BTW: the first example does not cache the result, you just copy the generator function. You may save a few microseconds of parsing time (because the function is already parsed, not really worth it)

So, no, it is not useful to cache the result of range in python 3 (in python 2, it would be useful, yes, since it creates an actual list).

like image 190
Jean-François Fabre Avatar answered Mar 30 '23 01:03

Jean-François Fabre


It won't make a noticeable difference, the majority of the time is spent inside of the loop, not generating the range object.

range in Python 3 returns a sequence, which means it will generate the values on the fly, without having to store them in a list.

like image 37
Francisco Avatar answered Mar 30 '23 02:03

Francisco