Skip to content

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

Compare Python's append(), extend(), and insert() methods to correctly add single elements, merge iterables, or place items at specific positions in lists.

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]

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]

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]

nums.insert(0, 0)
print(nums)  # [0, 1, 2, 3, 4]

Quick Comparison

Method Elements Added Position Time Complexity
append(x) 1 End O(1) ⚡
extend(iter) Multiple End O(k) ⚡
insert(i, x) 1 Index i O(n) 🐢

When insert(0) Becomes a Problem

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

from collections import deque

items = []
for i in range(10000):
    items.insert(0, i)

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)
Navigation