[Tutor] Why does counting to 20 million stress my computer?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Jul 17 20:47:40 CEST 2004


> using range(50000000): 	18.281 seconds
> using xrange(50000000):	13.516 seconds
>
> You sure you didnt type in 500000000 ;)
>
> So xrange is definitely quicker. Is it better to use xrange all the time
> in place of range then ?


Hi Nick,

It depends on what we need.  *grin*


xrange() returns an iterable object that's wonderful if we want to go
through the integers in order, one at a time.  But say we wanted to do
something, like grab a randomized list of numbers:

###
>>> import random
>>> numbers = range(52)
>>> random.shuffle(numbers)
>>> numbers
[1, 43, 18, 48, 47, 0, 46, 36, 13, 9, 20, 27, 42, 45, 10, 26, 19, 38, 16,
35, 25, 32, 17, 22, 23, 29, 6, 41, 14, 30, 15, 40, 50, 28, 3, 49, 12, 39,
5, 11, 33, 4, 34, 37, 24, 21, 2, 7, 8, 51, 31, 44]
###

In this case, range() is a good tool for this job, because it gives us a
list that we can munge up with random.shuffle().  xrange() gives us just
an iterable that's specialized only to do sequential counting, so it
wouldn't be as appropriate here.


Personally, I usually do stick with range(), and completely disregard
efficiency until I really need it.

Hope this helps!



More information about the Tutor mailing list