Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What is xrange?
#8
I started to write a simple implementation and the result was this monster:

But to understand it a bit better, here a stupid xrange:
import time

def xrange(stop):
   current = 0
   while True:
       if current < stop:
           yield current
           # the generator is suspended here
           # the state is saved in the generator
           current += 1
       else:
           break # stops the generator


generator = xrange(4)
print(next(generator))
time.sleep(1)
print(next(generator))
time.sleep(1)
print(next(generator))
time.sleep(1)
print(next(generator))
time.sleep(1)
print(next(generator))
Output:
0 1 2 3
Error:
StopIteration                             Traceback (most recent call last) <ipython-input-53-793910a0cbc2> in <module>()      8 print(next(generator))      9 time.sleep(1) ---> 10 print(next(generator)) StopIteration:
The manual call with next is what a for-loop does automatically and when a StopIteration is raised, the for-loop stops. You won't see this error.
As mentioned before xrange has been renamed to range in Python 3.

If you want to generate an output which does not fit into your memory, you should use xrange in Python 2.
Then you can iterate over the xrange object and do stuff with the numbers.

If you need a list from a range function in Python 3, you have to call list(range(n)).
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
What is xrange? - by failedSIGNAL - May-30-2017, 01:50 AM
RE: [SMALL QUESTIONS] - by Larz60+ - May-30-2017, 03:21 AM
RE: [SMALL QUESTIONS] - by failedSIGNAL - May-30-2017, 04:21 AM
RE: [SMALL QUESTIONS] - by buran - May-30-2017, 05:10 AM
RE: What is xrange? - by Ofnuts - Jun-01-2017, 09:50 AM
RE: What is xrange? - by ackmondual - Jun-13-2017, 11:27 PM
RE: What is xrange? - by nilamo - Jul-06-2017, 08:27 PM
RE: What is xrange? - by DeaD_EyE - Jul-07-2017, 09:22 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020