Lesson 36 +10 XP

Add and Remove List Items

Lists grow and shrink easily.

Add to the end with append

Code

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

### ['apple', 'banana', 'orange']

Add at an index with insert

Code

python
thislist.insert(1, "mango")
print(thislist)

### ['apple', 'mango', 'banana', 'orange']

Add another list with extend

Code

python
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

Code

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

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

Remove by index with pop

Code

python
thislist.pop(0)

### removes and returns index 0
thislist.pop()

### removes and returns the last item

Clear with clear

Code

python
thislist.clear()
print(thislist)

### []

The del keyword

del removes an item or the whole list:

Code

python
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.