I timed both range()
and xrange()
expecting range()
to be faster. But I got surprising results.
$ python -m timeit 'for i in range(1000000):' ' pass'
10 loops, best of 3: 39.9 msec per loop
$ python -m timeit 'for i in xrange(1000000):' ' pass'
10 loops, best of 3: 20.2 msec per loop
If I'm not mistaken, range()
stores the whole list in memory while xrange()
lazily evaluates the list.
So shouldn't accessing elements from the already generated list be faster than lazily evaluating the list and getting required elements? I don't get it.