Python Add List Items
Python gives you several ways to grow a list, whether you want to add one item, insert it at a chosen spot, or merge another collection in.
Adding to the end with append()
The append() method adds a single item to the very end of the list. It is the most common way to build a list up piece by piece, for example while collecting results inside a loop.
append() in action
animals = ["cat", "dog"]
animals.append("rabbit")
print(animals)The list grows to ['cat', 'dog', 'rabbit']. Note that append() changes the list in place and returns None, so you should not write animals = animals.append(...).
Inserting at a position with insert()
When you need an item at a specific spot rather than the end, insert() takes two arguments: the index where the item should go and the item itself. Everything from that index onward shifts one place to the right.
insert() at an index
animals = ["cat", "dog", "rabbit"]
animals.insert(1, "hamster")
print(animals)Inserting at index 1 gives ['cat', 'hamster', 'dog', 'rabbit']. The original 'dog' and 'rabbit' each moved one position to the right to make room.
Adding many items with extend()
extend() vs append()
a = [1, 2]
b = [3, 4]
a.extend(b)
print(a)extend() appends each element of another iterable one at a time, producing [1, 2, 3, 4]. If you used a.append(b) instead, you would get [1, 2, [3, 4]] because append adds the whole list as a single nested item.