Matt
Matt

Reputation: 3852

When using range() inside a for loop, in what procedure does the list instantiate?

I'm wondering about the range() function when used in a python for loop

for x in range(100):
    print x

Does range initialize the entire iter-able list before entering the loop or is it smart enough to generate the values as it increments?

In other words if I say. Will there be overhead from very large ranges like such?

  for x in range(1000**1000):
      value = x

Upvotes: 0

Views: 73

Answers (4)

ryanpattison
ryanpattison

Reputation: 6251

In Python 3, range produces an "immutable sequence" not a generator or iterator

In Python 2, range generates a list Python 2 also has xrange to make an object which is an "opaque sequence" which has virtually no memory overhead but xrange is not available in Python 3.

Upvotes: 2

NPE
NPE

Reputation: 500913

This depends on the Python version:

  • In Python 3, range() is a generator-like object that produces values on demand.
  • In Python 2, range() creates a materialised list. If you want a generator-like object, use xrange().

Upvotes: 2

Irshad Bhat
Irshad Bhat

Reputation: 8709

Yes! python initialize the entire iter-able list before entering the loop if range() is used. But there is an easy way of overcoming this overhead using xrange() which generate the values as it increments. This can be verified as:

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

Upvotes: 1

Simon
Simon

Reputation: 10841

In case of any doubt, it is easy to check. In IDLE (e.g. using Python 3.3):

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

Upvotes: 1

Related Questions