What is the difference between extending and append

Extending and Append difference.

Append adds its argument as a single element to the end of a list. The length of the list itself will increase by one. extend iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument

Extend adds all the elements from another iterable to the list at once, while append only does one at a time. This makes optimization possible in certain cases.

Inside of Python lists, there is a C array which is reallocated to twice its previous size whenever the array runs out of space for new items. If you use append, this may happen several times during the course of adding items. However, if you extend and the iterable you’re adding has a fixed length (i.e. not a generator or an iterator), the space will all be allocated in advance and that could allow you to avoid multiple reallocations.

I wouldn’t worry about it unless you’re actually having performance problems, however. Pypy can optimize a lot of this stuff out, and you can always rewrite hot loops in C or Cython. Native Python is kind of slow, and the best way to improve performance is often to simply rewrite trouble-spots in a faster language.