Python Lists · Lesson 42 of 149

Python List Add and Remove Items

What you will learn

  • How to change one item by its index
  • Adding items: append, extend, insert, and +=
  • Removing items: remove, pop, del, clear
  • Why these methods return None
  • How to remove every occurrence of a value

Lists are mutable: they change in place (lesson 2.6). Almost every method in this lesson changes the list itself and returns None, not a new list.

1. Changing one item

Assign to an index to replace the item there:

nums = [10, 20, 30]
nums[1] = 25
print(nums)
[10, 25, 30]

The index must already exist. You cannot make a list longer by assigning past its end:

nums[3] = 40
IndexError: list assignment index out of range

To grow a list, use one of the adding methods below.

Quick check: after `nums = [1, 2, 3]` and `nums[-1] = 9`, what is `nums`?

[1, 2, 9]. Negative indexes work for assignment too.

2. Adding items

append: one item at the end

nums = [10, 25, 30]
result = nums.append(40)
print(nums, result)
[10, 25, 30, 40] None

append changed the list and returned None. A common beginner mistake follows from this:

lst = [1, 2, 3]
lst = lst.append(4)
print(lst)
None

Write lst.append(4) alone, without lst = in front.

append adds exactly one item, even if that item is itself a list:

nums.append([50, 60])
print(nums, len(nums))
[10, 25, 30, 40, [50, 60]] 5

extend: many items

extend adds each item of another collection, one by one:

nums = [1, 2]
nums.extend([3, 4])
print(nums)
nums.extend((5, 6))
nums.extend("ab")
nums.extend(range(2))
print(nums)
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 'a', 'b', 0, 1]

It accepts any collection: a list, a tuple, a string (item by item, so letters) or a range.

append or extend?

Call Adds Result for [1, 2]
lst.append([3, 4]) the list as one item [1, 2, [3, 4]]
lst.extend([3, 4]) the items one by one [1, 2, 3, 4]
lst += [3, 4] same as extend [1, 2, 3, 4]

lst += other changes the same list, like extend. But lst = lst + other builds a new list (lesson 7.1). They look alike, but the difference matters when another name points to the same list (lesson 2.7):

x = [1, 2]
y = x + [3]
print(x, y)
[1, 2] [1, 2, 3]

insert: at a position

insert(index, item) puts the item before the given index and moves the rest up:

n = [10, 20, 30]
n.insert(1, 15)
print(n)
n.insert(0, 5)
n.insert(len(n), 99)
n.insert(100, "end")
print(n)
[10, 15, 20, 30]
[5, 10, 15, 20, 30, 99, 'end']

An index beyond the end simply puts the item at the end; a very negative one puts it at the start. For adding at the end, append is the normal choice.

3. Removing items

remove: by value

remove(value) deletes the first item that equals the value:

w = ["a", "b", "c", "b"]
w.remove("b")
print(w)
['a', 'c', 'b']

Only the first "b" went. If the value is not there, you get an error:

w.remove("z")
ValueError: list.remove(x): x not in list

Check with in first if the value may be missing.

pop: by position, and gives it back

pop() removes the last item and returns it. pop(i) removes the item at index i:

w = ["a", "b", "c", "d"]
last = w.pop()
print(last, w)
first = w.pop(0)
print(first, w)
print(w.pop(-1), w)
d ['a', 'b', 'c']
a ['b', 'c']
c ['b']

Unlike the other methods, pop gives back something useful. Popping from an empty list, or from a bad index, is an IndexError: [].pop() says pop from empty list.

del: by position or range

The del statement removes the item at an index, or a whole slice (lesson 7.3). It returns nothing:

d = [0, 1, 2, 3, 4, 5]
del d[0]
print(d)
del d[-1]
print(d)
del d[1:3]
print(d)
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 4]

del d[:] empties the list, and so does the method clear():

c = [1, 2, 3]
c.clear()
print(c, c == [])
[] True

Which removal?

You know Use
the value remove(value)
the position, and want the item back pop(i)
the position or a range, no need for the item del lst[i] or del lst[a:b]
nothing: empty it clear()

4. Removing every occurrence

remove deletes only the first match. To remove all of them, either repeat while the value is present, or build a new list without it:

nums = [1, 2, 1, 3, 1]
while 1 in nums:
    nums.remove(1)
print(nums)

nums = [1, 2, 1, 3, 1]
nums = [v for v in nums if v != 1]
print(nums)
[2, 3]
[2, 3]

The second form is a list comprehension (chapter 12), and it is usually the better choice. Never remove items inside a for loop over the same list (lesson 6.2).

5. Methods that return None

Always remember: these list methods change the list and return None:

append, extend, insert, remove, clear, sort, reverse

Only pop returns an item. So x = lst.sort() or lst = lst.reverse() leaves you with None. When you want a new list, use the function forms: sorted(lst) and list(reversed(lst)).

nums = [1, 2, 3]
nums.reverse()
print(nums)
[3, 2, 1]

Worked example: a waiting list

Customers join a waiting list at the end, the first customer is served from the front, and one customer leaves.

queue = []
queue.append("Rina")
queue.append("Sam")
queue.append("Lee")
queue.append("Mia")
print(queue)

served = queue.pop(0)
print("served:", served)
queue.remove("Lee")
queue.insert(0, "VIP")
print(queue)
['Rina', 'Sam', 'Lee', 'Mia']
served: Rina
['VIP', 'Sam', 'Mia']
Step Call List afterwards
4 join append four times Rina, Sam, Lee, Mia
serve pop(0) returns Rina Sam, Lee, Mia
leave remove("Lee") Sam, Mia
priority insert(0, "VIP") VIP, Sam, Mia

The names are made up. (For a real queue with many items, lesson 7.6 shows a faster tool.)

Common mistakes

  • Writing lst = lst.append(x). It stores None. Use lst.append(x).
  • Using append when you meant extend, which adds a list as one nested item.
  • Calling remove for a value that is not there. Check with in.
  • Assigning to an index past the end. Use append.
  • Removing items while looping over the same list.
  • Forgetting that remove deletes only the first match.

Key takeaways

  • lst[i] = v replaces an item; the index must exist.
  • append(x) adds one item; extend(items) and += add each item; insert(i, x) adds at a position.
  • remove(x) deletes the first matching value; pop(i) removes and returns an item; del removes by position or range; clear() empties the list.
  • These methods change the list and return None (only pop returns an item).
  • To remove all matches, loop while the value is present or build a new list.

Practice

1. Start with [1, 2, 3]. What is it after append(4) and then insert(0, 0)?

Show answer

[0, 1, 2, 3, 4].

2. What is the difference between a.append([5, 6]) and a.extend([5, 6])?

Show answer

append adds the list [5, 6] as one item. extend adds 5 and 6 as two items.

3. With colors = ["red", "green", "blue"], what does colors.pop(1) return and what is left?

Show answer

It returns "green", and colors is ["red", "blue"].

4. Why does nums = nums.sort() leave nums as None?

Show answer

sort() sorts the list in place and returns None, and the assignment stores that None. Write nums.sort() alone, or nums = sorted(nums).

5. Remove every 0 from [0, 3, 0, 5].

Show answer

[v for v in [0, 3, 0, 5] if v != 0] gives [3, 5].

6. What is the safe way to remove "x" from a list that may not contain it?

Show answer
if "x" in items:
    items.remove("x")