In Python 2 is it more pervasive to use range or xrange?

7

The programming language I use most is : (), and after it has been implemented Generators in version 5.5, it is said to be faster to use for generating numbers in sequence than with the function range - which creates a array with the sequence, unlike the Generator , which could generate one number at a time by yield .

Example range PHP:

range(1, 1000); // Retorna: [1, 2, 3, ..., 1000]

Example Generator PHP:

function xrange($start, $limit, $step = 1) {
    if ($start < $limit) {
        if ($step <= 0) {
            throw new LogicException('Step must be +ve');
        }

        for ($i = $start; $i <= $limit; $i += $step) {
            yield $i;
        }
    } else {
        if ($step >= 0) {
            throw new LogicException('Step must be -ve');
        }

        for ($i = $start; $i >= $limit; $i += $step) {
            yield $i;
        }
    }
}

The output would be:

xrange(); // Generator(object)

According to PHP staff, in a numerical sequence with range in PHP with 1000000 would use more than 100MB of memory, whereas with a Iterator that would do the same thing, would spend 1kb in memory.

Python

Based on this, I noticed that in Python the sequences generated by range are lists, other than the 3 version, which returns a Range object.

Also in Python there is a function called xrange (which is imitated by PHP in this page ), which returns a Generator .

The question is : Does range in Python return a list would not make this function more costly than memory, because of the list that is generated?

If I want to make a range from 1 to 1000 , in Python it would be more advisable to use xrange , or range itself would not hurt to memory consumption?

    
asked by anonymous 17.12.2015 / 19:43

1 answer

5

As you've raised, the range(x, y) function creates a list of elements from x to y .

The xrange(x,y) function generates each element individually, and this saves memory and startup time.

Remembering that in the case of 1000 elements, the drop in performance would be barely noticeable. But in larger proportions it could actually lead to a decrease in computer performance due to excessive memory consumption.

The performance of range() is worse, and the reason is simple, when you use for example the function like this:

for x in range(0, 1000000000):
    print x

The function creates a list of 1 billion elements and allocates it in memory.

Whereas with the function xrange() :

for x in xrange(0,1000000000):
    print x

The function generates the elements a single time saving memory and runtime.

    
17.12.2015 / 23:30