livepython.net
CHAPTER 09Python Lists
9.4  ADD, REMOVE

Add and Remove Items in a Python List

Add an Item with append()

append() adds one item to the end of a list. You write it after the list's name, with a dot: cart.append("eggs"). A function that belongs to a value like this is called a method.

Think of joining a queue: the new person always goes to the back.

PYTHONedit me
cart = ["milk", "bread"]
cart.append("eggs")
print(cart)
print(len(cart))
OUTPUT
['milk', 'bread', 'eggs']
3

The rules

  • list.append(item) adds the item at the end.
  • It changes the list itself. You don't need cart = ... in front.
  • It adds one item at a time.

Start empty, then fill up

The empty list from topic 1 is the usual starting point. Make it first, then append:

PYTHONedit me
guests = []
guests.append("Sunny")
guests.append("Rocky")
print(guests)
OUTPUT
['Sunny', 'Rocky']

It works with input() from chapter 7, too. Each input() reads one line, and append() stores it:

PYTHONedit me
todo = []
todo.append(input())
todo.append(input())
print(todo)
OUTPUT
['study', 'play']

Avoid: storing what append() gives back

PYTHONedit me
cart = ["milk"]
cart = cart.append("eggs")
print(cart)
OUTPUT
None

The list is gone! append() changes the list and gives back None, the "no value" from chapter 5. Then cart = ... stores that None. Write cart.append("eggs") on its own line.

Avoid: two items in one append()

PYTHONedit me
cart = ["milk"]
cart.append("eggs", "jam")
OUTPUT
TypeError: list.append() takes exactly one argument (2 given)

An argument is a value you put in the brackets. append() takes exactly one. To add two items, call it twice.

list.append(item) adds one item to the end of the list.

your turnFill the gap

Add dog to the end of the list

pets = ["cat"] pets.?("dog") print(pets)

It should print: ['cat', 'dog']

Which piece makes this code work?

Add an Item Anywhere with insert()

insert() puts an item at any index you choose: list.insert(index, item). The items from that index on move one place to the right.

Think of a friend saving you a spot in a queue. You step in at that spot, and everyone behind you moves back by one.

PYTHONedit me
menu = ["tea", "juice"]
menu.insert(0, "water")
print(menu)
menu.insert(2, "coffee")
print(menu)
OUTPUT
['water', 'tea', 'juice']
['water', 'tea', 'coffee', 'juice']

The rules

  • The index comes first, then the item.
  • insert(0, item) adds at the front.
  • Nothing is replaced. The list gets one item longer.
  • An index past the end adds the item at the end, with no error.
PYTHONedit me
nums = [1, 2]
nums.insert(10, 3)
print(nums)
OUTPUT
[1, 2, 3]

append() or insert()?

MethodWhere the item goesValues in the brackets
append(item)at the endone
insert(index, item)at that indextwo

Good: append() when the place doesn't matter, or the item belongs at the end. It's shorter and clearer.

Avoid: insert(len(menu), item). It works, but append(item) says the same thing more simply.

Common mistake: the values swapped

PYTHONedit me
menu = ["tea"]
menu.insert("coffee", 0)
OUTPUT
TypeError: 'str' object cannot be interpreted as an integer

Python expected a whole number first, the index, but got the string "coffee". Index first, item second.

list.insert(index, item) puts the item at that index and moves the rest to the right.

your turnPredict the output

What will this print?

nums = [10, 30] nums.insert(1, 20) print(nums)
Your turn! What will this code show on the screen?

Remove an Item by Value with remove()

remove() takes an item out of a list by its value: cart.remove("bread"). Python finds the first item equal to that value and removes it.

Think of crossing an item off your shopping list. You look for the word "bread" and strike it out. You don't need to know which line it was on.

PYTHONedit me
cart = ["milk", "bread", "eggs"]
cart.remove("bread")
print(cart)
OUTPUT
['milk', 'eggs']

The rules

  • remove() looks for a value, not an index.
  • It removes only the first match.
  • The items after it move one place left, so the list gets one item shorter.
  • If the value isn't in the list, Python stops with a ValueError.

Only the first match

PYTHONedit me
votes = ["yes", "no", "yes"]
votes.remove("yes")
print(votes)
OUTPUT
['no', 'yes']

The second "yes" stays. To remove it too, call remove() again.

When the value isn't there

PYTHONedit me
cart = ["milk", "eggs"]
cart.remove("bread")
OUTPUT
ValueError: list.remove(x): x not in list

Don't be scared of this error! The x stands for the value you gave, "bread". Python is saying: "I looked, and it isn't in this list". In topic 5, you'll learn in, which checks first.

Common mistake: remove(0) for the first item

PYTHONedit me
nums = [5, 0, 7]
nums.remove(0)
print(nums)
OUTPUT
[5, 7]

remove(0) doesn't remove the first item. It removes the value 0. To remove by position, use pop() or del, in the next lesson.

list.remove(value) removes the first item with that value.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Remove by Index with pop() and del

pop() removes an item by its index and gives it back to you. With no index, it takes the last item. del removes an item by its index and gives nothing back.

Think of a stack of plates. You pop the top plate off, and now it's in your hand, ready to use.

PYTHONedit me
plates = ["plate 1", "plate 2", "plate 3"]
top = plates.pop()
print(top)
print(plates)
OUTPUT
plate 3
['plate 1', 'plate 2']

pop(0) takes the first item. That's how a queue serves the person at the front:

PYTHONedit me
queue = ["Sunny", "Rocky", "Lucky"]
first = queue.pop(0)
print(f"Now serving {first}")
print(queue)
OUTPUT
Now serving Sunny
['Rocky', 'Lucky']

When you don't need the item any more, del is enough:

PYTHONedit me
scores = [10, 0, 30]
del scores[1]
print(scores)
OUTPUT
[10, 30]

The rules

You knowUseGives back
the valuelist.remove(value)nothing
the index, and you need the itemlist.pop(index)the item
you want the last itemlist.pop()the item
the index, and you don't need the itemdel list[index]nothing

del is not a method, so there's no dot: write del scores[1], not scores.del(1).

Avoid: popping what isn't there

PYTHONedit me
empty = []
empty.pop()
OUTPUT
IndexError: pop from empty list

An empty list has nothing to pop. An index that's too big fails too: [1, 2].pop(5) gives IndexError: pop index out of range. Check the length with len() first, as you did in topic 2.

pop() removes an item by index and gives it back. del list[i] removes it and gives nothing back.

your turnOrder the lines

Put the lines in order to print the finished task, then the rest

  1. done = tasks.pop(0)
  2. print(tasks)
  3. print(f"Done: {done}")
  4. tasks = ["cook", "clean", "shop"]
These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

# print("A") print("B")
Your turn! What will this code show on the screen?

Practice: Add, remove

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 76.Python Program to Add Items to a Shopping ListEasySolve
  2. 77.Python Program to Remove a Task by Its NumberMediumSolve