Loading lessons...
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
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.