January 16, 2016

On the efficiency of extended iterable unpacking in python3

At the very beginning of PEP3132 you can read:

Many algorithms require splitting a sequence in a "first, rest" pair. With the new syntax,
 first, rest = seq[0], seq[1:]  

is replaced by the cleaner and probably more efficient:

 first, *rest = seq  

I run sum tests where I compared classical list slicing and the new * operator for unpacking. I found out the exact opposite: list slicing not only is better, but it runs in $O(1)$ in certain cases. The first test was against the iterable returned by range(a,b), while the second was against the list on the same range(a,b).


"""" OUTPUT
calculating average with range()
AVG of   list sl         extended
10**2    0.00002         0.00002
10**3    0.00002         0.00006│
10**4    0.00002         0.00045│
10**5    0.00001         0.00863
10**6    0.00002         0.08700

calculating average with list(range())
AVG      list sl         extended
10**2    0.00002         0.00002
10**3    0.00003         0.00002
10**4    0.00010         0.00011
10**5    0.00110         0.00114
10**6    0.01114         0.02591
""""