Search code examples
pythontimertimeit

Pop from empty list


I wanna calculate the time of 'pop'. here is the code.

x=list(range(10000))
popz=timeit.Timer("x.pop(0)","from __main__ import x")
print (popz.timeit())
IndexError: pop from empty list

How can I get the time of pop from the beginning of the list.


Solution

  • By default, the timeit method runs a million times. However, your list is only 10000 items long. So when timeit runs, the first 10000 times will happily pop, but the 10001 iteration will fail. You can set the number of times explicitly:

    popz.timeit(n=10000)
    

    but ... this is a really tricky timing situation since you want to time how long it takes to .pop, but the size of your list is constantly changing. If you're looking for the asymptotic performance, you probably could verify that .pop(0) has asymptotic performance of O(N). However concrete times are going to be hard to come by since you either have to time the amount of time it takes to create the list along with the .pop, or you're list is constantly changing while you're timing it. Neither of these is ideal ... But I guess that's the problem with trying to time non-idempotent methods...