Re:A Hodgepodge of Python
by lysium on Thursday September 15, 2011 @05:15PM
(#3002164)
Didn't know the timeit module. However, the presented usage to time list reversing is ill: The timing is dominated by the list creation, which should go into setup. Then I'll get:
So, instead of reversing the list in place, creating a new, reversed list seems to be faster.
[ Parent
| on HN ]
>>> reversed([])
<listreverseiterator object at 0xb73ff7cc>
reversed() does not create a new list, it just returns a reverse-order view of the same list. Of course, often this is exactly what is needed.And more often than not `xrange` is what one needs, not `range`. (Not relevant with Py3k though, but everyone is still in 2.x-verse.)
>>> xrange(13)[::-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice' >>> list(range(13)[::-1]) == list(xrange(12, -1, -1))
True