Python Tutorial
Python Add List Items
append() adds at the end, insert() adds at an index, extend() adds all items from another iterable.
append()
Add an item to the end of the list.
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)insert()
Insert at a specified index. Existing items shift right.
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)extend()
Append elements from another list, tuple, set, or any iterable.
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple"]
thislist.extend(tropical)
print(thislist)📘 Real-World Deep Dive
Adding items to a list — append, extend, insert, plus the trade-offs of <code>+</code>, <code>+=</code>, and slicing assignment — shows up everywhere. Picking the right one is the difference between O(1) and O(n).
Real-Life Scenario
Two ways to ingest a stream into a list: append one-by-one, vs. extend with a slice. Show the same end result, distinct allocations.
Real-Life Example
a: list[int] = []
for x in range(5):
a.append(x) # O(1) each; keeps existing backing storage
print("a:", a)
b: list[int] = []
b.extend(range(5)) # single C-level call; newer memory
print("b:", b)
# Inserting in the middle
a.insert(2, 99) # O(n) due to shift
print("after insert:", a)
# '+' vs '+=' semantics
c = a + [100, 101] # new list
print("c (new):", c, "id different from a:", id(c) != id(a))
a += [200, 201] # in-place extend
print("a (in-place):", a, "id unchanged:", id(a) == a.__hash__())Expected Output
a: [0, 1, 2, 3, 4]
b: [0, 1, 2, 3, 4]
after insert: [0, 1, 99, 2, 3, 4]
c (new): [0, 1, 99, 2, 3, 4, 100, 101] id different from a: True
a (in-place): [0, 1, 99, 2, 3, 4, 200, 201] id unchanged: TrueCommon mistakes
a = a + bcreates a new list;a += bextends in place (forlist).- Inserting at the head of a large list is O(n); consider
deque.appendleft. - Repeated
list.append(other_list)gives a nested list — useextendinstead.
🚀 Performance & Best Practices
extend(iterable)is C-fast and often beatsappendin a loop.- Building a list then joining is faster than concatenating strings in a loop.
- Pre-allocate with
[None] * nif you know the size up front.
🧪 Try It Yourself
- Refactor
appendin a hot loop toextendwith a generator and benchmark. - Implement
push_many(xs, i, items)that splicesitemsat positioni. - Profile
listvs.collections.dequefor a queue with 1 M push/pops.