2

Assume that I have the following list of lists:

a = []
for i in range(500):
    a.extend([list(np.random.randn(50))])

If I was to add lists of the list a to another list I could use either + or extend. I make the assumption that + and += should have the same speed but it seems to be not the case. Here are my codes and the results:

%%timeit

b = []
for number in a:
    b = b + [number]
-------------------
321 µs ± 3.11 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit

b = []
for number in a:
    b += [number]
-------------------
26.4 µs ± 117 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Why there is such a huge difference in performance?

Mathemagician
  • 431
  • 4
  • 13
  • 1
    I'm not sure about that duplicate, but it's not that complicated anyway: `b = b + [number]` could be `c = b + [number]`, leaving `b` intact. So `+` makes a copy, which just happens to end up stored back in `b` here. `b += [number]` doesn't make a copy, it knows for sure that the original list doesn't need to be preserved. – tevemadar Mar 09 '22 at 08:39
  • For anyone wondering here is a more complete answer: [https://stackoverflow.com/questions/15376509/when-is-i-x-different-from-i-i-x-in-python](https://stackoverflow.com/questions/15376509/when-is-i-x-different-from-i-i-x-in-python) – Mathemagician Mar 09 '22 at 09:36

0 Answers0