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
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 actuallist
).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.