Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What is xrange?
#1
I'm about to create this thread to post some small questions to understand more about the instinct of some stuffs.
My first question: what (really) is 'xrange'? I tried to assign it to a variable then printed it out but I just got 'xrange(2)' (for example).
Meanwhile, 'range' really created a list (I tested it).
Reply
#2
xrange became range in python 3
Reply
#3
Sorry, that's my mistake. But your answer isn't satisfied me. I wanna refer to python 2. What is it? A module or something..
Reply
#4
xrange() is built-in function that returns xrange object, i.e. it will produce the same sequence as range(), but without storing all of the elements in the memory. for short one it's the same, difference comes with large sequence. you can iterate over it yielding one number at a time or pass it as argument 'everywhere where iterator is expected
As Larz60+ said in python3 it become range.
>>> for n in xrange(5):
...     print n
... 
0
1
2
3
4
>>> list(xrange(3))
[0, 1, 2]
>>> [n**2 for n in xrange(4)]
[0, 1, 4, 9]
the docs are more or less clear
Reply
#5
In python2 xrange(..) creates the values when they are needed (ie, when your code asks for the next value...), while range() generates all the possible values at once. No big difference when you are using small ranges, but vital if you are using large ranges, especially if your logic makes it unlikely that you use up all the generated values.

# this requires 4 MB to run:
sumOfSquares=0
for n in range(1000000):
   sumOfSquares+=n*n
 
# this requires 8 bytes to run:
sumOfSquares=0
for n in xrange(1000000):
   sumOfSquares+=n*n
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#6
(Jun-01-2017, 09:50 AM)Ofnuts Wrote: In python2 xrange(..) creates the values when they are needed (ie, when your code asks for the next value...), while range() generates all the possible values at once. No big difference when you are using small ranges, but vital if you are using large ranges, especially if your logic makes it unlikely that you use up all the generated values.

# this requires 4 MB to run:
sumOfSquares=0
for n in range(1000000):
   sumOfSquares+=n*n
 
# this requires 8 bytes to run:
sumOfSquares=0
for n in xrange(1000000):
   sumOfSquares+=n*n
Daaamn! That's a factor of half a million! Shocked
Reply
#7
It's just like range(), except it only generates numbers as you ask for them (instead of all at once).  If you wanted to see what it looks like in practice, here's a bad version I just made up:

>>> class xrange:
...   def __init__(self, min=0, max=None, step=1):
...     if max is None:
...       max = min
...       min = 0
...     self.max = max
...     self.step = step
...     self.current = min
...   def __iter__(self):
...     return self
...   def __next__(self):
...     value = self.current
...     self.current += self.step
...     if self.step > 0:
...       if value >= self.max:
...         raise StopIteration()
...     else:
...       if value <= self.max:
...         raise StopIteration()
...     return value
...
>>> for i in xrange(5):
...   print(i)
...
0
1
2
3
4
>>> for i in xrange(2, 12, 3):
...   print(i)
...
2
5
8
11
Reply
#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


Forum Jump:

User Panel Messages

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