Explore Courses Blog Tutorials Interview Questions
+2 votes
in Python by (3.5k points)
edited by

What makes using range() to make the process of generating a quadrillion values in a instant of time, I am amazed by this can anyone answer this question?

I also tried to run my own function but it didn't helped me:

def my_crappy_range(N):
    o = 0
    while o< N:
        yield o
        o += 1

2 Answers

0 votes
by (2k points)
edited by

The reason behind the speed is that in Python 3+ we're using mathematical reasoning about the bounds instead of a direct iteration. It just check all the objects between start and stop and stride value doesn't step over the numbers.

For Ref. you can check the following code:

>>> y, x = 10000000000000, range(10000000000001)
>>> class MyInt(int):
...     pass
>>> y_ = MyInt(y)
>>> y in x  # calculates immediately :)
>>> y_ in x  # iterates for ages.. :(
^\Quit (core dumped)

Happy Learning.

0 votes
by (106k points)
edited by
  • Due to optimization, it is very easy to compare given integers just with min and max range.
  • The reason that range() function is so fast in Python3 is that here we use mathematical reasoning for the bounds, rather than a direct iteration of the range object.
  • So for explaining the logic here:-
    • Check whether the number is between the start and stop, and
    • Check whether the step precision value doesn't go over our number.
  • Take an example, 997 is in range(4, 1000, 3) because:

4 <= 997 < 1000, and

(997 - 4) % 3 == 0.

  • range()  is a sequence, just like a list,and sequences are very fast to work with, It can be tested by below that range() is a sequence given example:-


a = range(5)



You can use the following video tutorials to clear all your doubts:-

Learn more about Python from an expert. Enroll in our Python Course

Browse Categories