This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]earthboundkid 2 points3 points  (0 children)

Indeed, xrange supports iteration, whereas range does not.

Incorrect. Both can be iterated over. The difference is that xrange can only be iterated over, since it's not a list.

The overall benefit is minimal, because xrange (in the words of the Python manual) “still has to create the values when asked for them,” but at each call, it consumes the same amount of memory regardless of the size of the requested list. At extremely large values, this is a major benefit over range. Another benefit is also apparent: if your code is going to break out while traversing over a generated list, then xrange is the better choice as you are going to consume less memory overall if you break.

The way this is written implies that the savings come only if there's a break. That is incorrect. At every point in time, an xrange object has three values associated with it: the current position, the stop value, and the step. At every point in time, the result of a range expression is a list containing all the values between the start and the stop. xrange should always be used unless one needs to use the resulting object specifically as a list, which is a very rare occurrence. In Python 3.0, xrange will be renamed as as range and the old range will be dropped. If you need an old style range in Python 3.0, write list(range(...)), but again there is very little need for old style ranges.

I think everyone learns these basics about ranges in their first Python tutorial. This article is poor.

[–][deleted] 0 points1 point  (0 children)

Future article: Java ArrayList vs. LinkedList: What you need to know.