Questions tagged [xrange]

xrange is a Python function that, unlike the traditional 'range' function, creates an iterator object rather than a list.

xrange is a Python function that, unlike the traditional range function, creates an iterator object rather than a list.

Their behaviors are very similar, but behind the scenes it's different.

range returns a list:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10).__class__
<type 'list'>
>>> for i in range(10):
...     print i,
0 1 2 3 4 5 6 7 8 9

xrange returns an iterable object:

>>> xrange(10)
xrange(10)
>>> xrange(10).__class__ #It's not a list, it's a class of its own.
<type 'xrange'>
>>> for i in xrange(10): #However, it can still be iterated over.
...     print i,
0 1 2 3 4 5 6 7 8 9

While they behave basically the same, xrange works differently. range generates a list and then returns it. xrange, typically used for low-memory systems or very large ranges, generates the numbers one at a time, once on each iteration rather than all at once before the loop.

Questions that include this tag should be related to xrange, not just code that happens to include it. Here are some relevant questions:

Relevant links:

91 questions
-4
votes
1 answer

Python - memory efficiency - range

I am seeking ways to make the below minimal code for MaxPower() function more memory efficient & examples using my code. Purpose of MaxPower(): for integers i and N_remainder, to return the maximum value of m such that i^m divides N_remainder.…
unseen_rider
  • 324
  • 5
  • 23
1 2 3 4 5 6
7