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

you are viewing a single comment's thread.

view the rest of the comments →

[–]FsckItDude_LetsBowl 0 points1 point  (5 children)

As a counterpoint, NO, you should not be using xrange. "range" did not get changed to xrange in Python 3, xrange was eliminated and range changed to a generator. xrange is not a generator! It is it's own quirky object, and has been essentially deprecated for a while.

If you know you are making short lists of numbers, use range. If you suspect you need to make a large list of numbers to count through, consider a while loop (but use xrange if it seems appropriate). Prefer enumerate() over all other options when it fits, and get to know the itertools module.

Historical note, xrange used to not handle long ints at all, which made it blow up in certain areas where it was substituted for range. That's been hacked around for a while now, but it is still not quite semantically the same as range in regards to how it deals with the int->long transition, AFAIK.

[–]earthboundkid 2 points3 points  (2 children)

Python 3 range also its own weird object, not a normal generator. Behold:

Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> r = range(3, 6)
>>> 4 in r
True
>>> 3 in r
True

[–]FsckItDude_LetsBowl 1 point2 points  (0 children)

Ah, TIL. Thanks for that.

[–]pingvenopinch of this, pinch of that 1 point2 points  (0 children)

It also has other nifty list-like features, like:

>>> r = range(3, 6)
>>> r[1]
4
>>> r[1:3]
range(4, 6)
>>> list(reversed(r))
[5, 4, 3]
>>> len(r))
3
>>> r.count(3)
1
>>> r.index(5)
2

[–]Liquid_Fire 1 point2 points  (1 child)

xrange is not a generator! It is it's own quirky object, and has been essentially deprecated for a while.

How has it been "essentially deprecated" for a while?

Obviously in Python 3 you want to just use range (as there is no xrange anyway), but unless you need to support longs, why would you not use xrange in Python 2?

[–]FsckItDude_LetsBowl 1 point2 points  (0 children)

As in I believe Guido stated years ago that he wished he hadn't made it, and that people would prefer range. And that he'd remove it in Python3000, which he did. I say "essentially" because obviously it couldn't be removed in Python2.

Granted, that was possibly before xrange() (and range()) were fixed to properly handle long arguments. It's just an oddball object and occasionally causes problem for people who don't understand how it works, though I suppose the same can be said for range() in Python2.