Reputation: 3852
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
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
Reputation: 500913
This depends on the Python version:
range()
is a generator-like object that produces values on demand.range()
creates a materialised list. If you want a generator-like object, use xrange()
.Upvotes: 2
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
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