Why or why not?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Go with range for these reasons:
1) xrange will be going away in newer Python versions. This gives you easy future compatibility.
2) range will take on the efficiencies associated with xrange.
xrange()
is more efficient because instead of generating a list of objects, it just generates one object at a time. Instead of 100 integers, and all of their overhead, and the list to put them in, you just have one integer at a time. Faster generation, better memory use, more efficient code.Unless I specifically need a list for something, I always favor
xrange()
Okay, everyone here as a different opinion as to the tradeoffs and advantages of xrange versus range. They're mostly correct, xrange is an iterator, and range fleshes out and creates an actual list. For the majority of cases, you won't really notice a difference between the two. (You can use map with range but not with xrange, but it uses up more memory.)
What I think you rally want to hear, however, is that the preferred choice is xrange. Since range in Python 3 is an iterator, the code conversion tool 2to3 will correctly convert all uses of xrange to range, and will throw out an error or warning for uses of range. If you want to be sure to easily convert your code in the future, you'll use xrange only, and list(xrange) when you're sure that you want a list. I learned this during the CPython sprint at PyCon this year (2008) in Chicago.
No, they both have their uses:
Use
xrange()
when iterating, as it saves memory. Say:rather than:
On the other hand, use
range()
if you actually want a list of numbers.One other difference is that xrange() can't support numbers bigger than C ints, so if you want to have a range using python's built in large number support, you have to use range().
Python 3 does not have this problem:
You should favour
range()
overxrange()
only when you need an actual list. For instance, when you want to modify the list returned byrange()
, or when you wish to slice it. For iteration or even just normal indexing,xrange()
will work fine (and usually much more efficiently). There is a point whererange()
is a bit faster thanxrange()
for very small lists, but depending on your hardware and various other details, the break-even can be at a result of length 1 or 2; not something to worry about. Preferxrange()
.