Skip to main content

How to Add Elements to a List in Python: append() vs extend() vs insert()

Python provides three built-in methods to add elements to a list: append(), extend(), and insert(). Each behaves differently and choosing the wrong one leads to unexpected bugs.

Using append() for Single Elements

The append() method adds one object to the end of a list:

nums = [1, 2]
nums.append(3)
print(nums) # [1, 2, 3]
warning

Appending a list creates a nested structure, not a merged list:

nums = [1, 2, 3]
nums.append([4, 5])
print(nums) # [1, 2, 3, [4, 5]]

Using extend() to Merge Iterables

The extend() method unpacks an iterable and adds each element individually:

nums = [1, 2]
nums.extend([3, 4])
print(nums) # [1, 2, 3, 4]

# Works with any iterable
nums.extend(range(5, 8))
print(nums) # [1, 2, 3, 4, 5, 6, 7]

The += operator is equivalent to extend():

nums = [1, 2]
nums += [3, 4] # Same as nums.extend([3, 4])
print(nums) # [1, 2, 3, 4]

Using insert() for Specific Positions

The insert() method places an element at a given index:

nums = [1, 3, 4]
nums.insert(1, 2) # Insert 2 at index 1
print(nums) # [1, 2, 3, 4]

# Insert at the beginning
nums.insert(0, 0)
print(nums) # [0, 1, 2, 3, 4]
Performance Consideration

insert() has O(n) time complexity since all subsequent elements must shift. Avoid frequent insertions at position 0 on large lists.

Quick Comparison

MethodElements AddedPositionTime Complexity
append(x)1EndO(1) ⚡
extend(iter)MultipleEndO(k) ⚡
insert(i, x)1Index iO(n) 🐢

When insert(0) Becomes a Problem

For frequent insertions at the beginning, use collections.deque instead:

from collections import deque

# Slow: O(n) per insertion
items = []
for i in range(10000):
items.insert(0, i)

# Fast: O(1) per insertion
items = deque()
for i in range(10000):
items.appendleft(i)

Summary

  • append(): Add single items to the end
  • extend(): Merge lists or add multiple elements
  • insert(): Add at specific positions (use sparingly on large lists)