巴扎黑2017-04-17 13:38:06
I accidentally saw this paragraph while reading "Python Learning Notes" by Q.yuhen. I wanted to add an answer to this question, so I cut the picture and turned it over:
PHPz2017-04-17 13:38:06
Everyone upstairs talks about the advantages of xrange, I will add the disadvantages
1. python3 does not have xrange. If you migrate python2 to 3, or you want to run programs on 2/3 at the same time, you should pay attention.
2. xrange does not support slicing, which may not be very enjoyable to use.
Personally, if the amount of data is not large, you should still use range. If the data is large and it is version 2, consider using xrange.
ps: Get to know both, and then choose the one that best suits your needs~~There is really no absolute~~
黄舟2017-04-17 13:38:06
range(start, end, step) will generate a list [start, start+step, start+2*step, ..., end]
If the difference between start and end is large, it will take a long time to generate the list, and the amount of data will be large and occupy memory. After generation, iterate again.
xrange(start, end, step) will not generate a list. It will generate one number at a time and will not affect memory.
ringa_lee2017-04-17 13:38:06
Python 3 only has range
, which has the same effect as Python 2’s xrange
~~
PHP中文网2017-04-17 13:38:06
Select range
for normal programs, and use xrange
for operations that may be time-consuming.
阿神2017-04-17 13:38:06
You can Google the implementation differences between range() and xrange().
If the number in the range is not large, use range(); otherwise use xrange(). As for how big the number is, I will go with my feeling
There is only range() in Python 3.x, but you know about Python version issues and maintenance issues.
大家讲道理2017-04-17 13:38:06
xrange finally returns a generator
range is a list (python2.7)
I personally like xrange a bit