Lesson 36 +10 XP

Add and Remove List Items

Add and Remove List Items

Lists grow and shrink easily.

Add to the end with append

thislist = ["apple", "banana"]
thislist.append("orange")
print(thislist)  # ['apple', 'banana', 'orange']

Add at an index with insert

thislist.insert(1, "mango")
print(thislist)  # ['apple', 'mango', 'banana', 'orange']

Add another list with extend

more = ["cherry", "kiwi"]
thislist.extend(more)
print(thislist)  # ['apple', 'mango', 'banana', 'orange', 'cherry', 'kiwi']

extend() also works with tuples, sets, and dicts.

Remove by value with remove

thislist.remove("banana")
print(thislist)

Removes the FIRST matching item. Raises ValueError if it's not found.

Remove by index with pop

thislist.pop(0)  # removes and returns index 0
thislist.pop()   # removes and returns the last item

Clear with clear

thislist.clear()
print(thislist)  # []

The del keyword

del removes an item or the whole list:

del thislist[0]   # delete one item
del thislist      # delete the whole list

TL;DR

  • append adds at the end; insert adds at an index.
  • extend joins another collection.
  • remove deletes by value; pop deletes by index (and returns it).
  • clear empties the list; del removes items or the list itself.