I tested two different ways to access a list in python.
import timeit value = [i for i in range(100)] def rev1(): v = [] for i in value: v.append(i) v.reverse() def rev2(): v = [] for i in value: v.insert(0, i) print timeit.timeit(rev1) print timeit.timeit(rev2)
Interestingly, the second method, which inserts a value into the first element, is much slower than the first.
20.4851300716 73.5116429329
Why is this? From an operating point of view, inserting an element into the head does not seem so expensive.
python list algorithm reverse
prosseek
source share