Python range and xrange


In Python 2.x, the function range(x, y, s) generates a actual list of elements from to y – 1 step s.  The other syntax is range(a) and range(a, b) which is the same as range(0, a, 1) and range(a, b, 1) respectively. For example,

>>> range(1, 10, 3)
[1, 4, 7]

This is inefficient if you create a list that contains a large number of elements (e.g. millions), because in memory, the elements are actually created and preserved. This is bad if you don’t actually need all elements but just using that in a loop (one by one).

Instead, you can use function xrange(x, y, s) to generate an element one by one.  So instead of writing:

for i in range(10000000):
    print i

You can write this in a more efficient manner:

for i in xrange(10000000):
    print i

If you type xrange in the prompt, you will just get a generator:

>>> xrange(1, 10, 3)
xrange(1, 10, 3)

To make this a list, you will have to put the generator in the list.

>>> list(xrange(1, 10, 3))
[1, 4, 7]

So, if you just need a iterator for loop, always prefer xrange because of memory performance advantages. However, there is no better ways if you do need a whole list of elements.

In Python3, there is no xrange() any more. The range in Python3 is actually xrange which is a generator in Python2. So you will have to put a list wrapping range if you need a list of elements.

To make your Python code work both in Python 2.x and 3.x, you can use the following checks:

import sys
PYTHON3 = sys.version_info[0] == 3

if PYTHON3:
    xrange = range

So this will force xrange calls to range which is the generator in Python 3.x.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
397 words
Last Post: Lost Era, MS-DOS 16-bit Assembly, Generate a DOS .COM Message Print using Python, Write Binary Code
Next Post: Coding Exercise - String to Integer (atoi) - C++ - Online Judge

The Permanent URL is: Python range and xrange

Leave a Reply