In python, we can concatenate lists in two ways:
- lst.extend(another_lst)
- lst += another_lst
I thought extend
would be faster than using +=
, because it reuses the list instead of creating a new one using the other two.
But when I test it out with timeit
, it turns out that +=
is faster,
>>> timeit('l.extend(x)', 'l = range(10); x = range(10)')
0.16929602623
>>> timeit('l += x', 'l = range(10); x = range(10)')
0.15030503273
>>> timeit('l.extend(x)', 'l = range(500); x = range(100)')
0.805264949799
>>> timeit('l += x', 'l = range(500); x = range(100)')
0.750471830368
Is there something wrong with the code I put in timeit
?