Range is used exactly the same as xrange, and the difference is that the return result is different: Range returns a list, and Xrange returns a generator. can look at the
1 Print type (range (5))23print type (xrange (5))45 6# print Result: <type ' list ' >7# <type ' Xrange ' >
You can see that their return type is not the same, one is a list, one is xrange, that is, the range returns need to open up a memory space to store the list, and Xrange is the return of each call one of the values, that is, by an algorithm to calculate the subsequent values, This avoids the need to create a full list.
1 Print range (5)23# printing results: [0, 1, 2, 3, 4]45 Print xrange (5)67# Printing results: xrange (5)
As you can see, Range creates a complete list, and xrange is not. The benefit of xrange is that it consumes less memory and is more efficient than range, especially when it needs to be back very large. Here's a look at the code:
1 Import Time2 3 defrange_time ():4Time1 =time.time ()5 forIinchRange (0, 1000000):6 Pass7Time2 =time.time ()8 PrintTime2-time19 Ten defxrange_time (): OneTime1 =time.time () A forIinchXrange (0, 1000000): - Pass -Time2 =time.time () the PrintTime2-time1 - - range_time () - xrange_time () + - #Print Result: 0.0380001068115 + #0.0179998874664
You can see that range execution time is 0.0380001068115,xrange to 0.0179998874664,xrange efficiency is significantly higher than range, so try to use xrange unless you need to return a list.
Note: Python has no range in the 3.x version and has changed xrange to range.
Range and Xrange