What is the Difference between append and insert?

Hi I just learned in Python how to insert items into a list. It seems very similar to using append and I wondered what the difference was. Thanks!

In simplest terms, .append() can only add an item to the end of a list, while .insert() can place it anywhere in the list, since its first argument is an index:

a = [1, 2, 4]
a.insert(2, 3)

print(a)
[1, 2, 3, 4]

The documentation reads:

list.append(x)
Add an item to the end of the list. Equivalent to a[len(a):] = [ x ].

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

https://docs.python.org/3/tutorial/datastructures.html

2 Likes

thanks! That makes sense.

2 Likes