Loading lessons...
Add and Remove List Items
Lists grow and shrink easily.
Add to the end with append
python
thislist = ["apple", "banana"]
thislist.append("orange")
print(thislist)
### ['apple', 'banana', 'orange']
Add at an index with insert
python
thislist.insert(1, "mango")
print(thislist)
### ['apple', 'mango', 'banana', 'orange']
Add another list with extend
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
python
thislist.remove("banana")
print(thislist)
Removes the FIRST matching item. Raises ValueError if it's not found.
Remove by index with pop
python
thislist.pop(0)
### removes and returns index 0
thislist.pop()
### removes and returns the last item
Clear with clear
python
thislist.clear()
print(thislist)
### []
The del keyword
del removes an item or the whole list:
python
del thislist[0]
### delete one item
del thislist
### delete the whole list
TL;DR
appendadds at the end;insertadds at an index.extendjoins another collection.removedeletes by value;popdeletes by index (and returns it).clearempties the list;delremoves items or the list itself.