Monday, September 22, 2008

range vs xrange

In Python, you can create a list of numbers (arithmetic progression) using range( )

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range( 2, 10, 2)
[2, 4, 6, 8]

>>> type(range(10))

range() returns a list of numbers - We may not need an explicit list for most of our purposes - We may require only one item of the list at any point of time for typical applications -

for i in range(10):
print i

While executing the above code, the call to range(10) creates a list with elements [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. Then, i iterates over this list. However, creating the list this takes up memory, which is not actually required.

We can use a generator based method xrange() - xrange can be used instead of range in most applications where you do not require all the elements to be in memory.

for i in xrange(10):
print i

This code will behave identical to the previous version of the code that uses range(10) - However, memory is saved since it uses a generator based approach than creating the whole list in memory.

You can check that it does not produce the entire list:
>>> type(xrange(10))

xrange is an iterable container, that returns only the next element in the list. So, whenever you don't need the entire list in memory, go ahead use xrange() and save some memory :-)

No comments: