Deleting from a List - Lakelands Computing

Title
Go to content
Deleting Items from a List
There are three ways in python to delete an item from a list:  remove , del and pop. They all get rid of the item but do it in a different way.

Remove
  • bands = ["foo fighters","guns n roses","oasis","greenday","metallica","oasis","the cure", "one direction", "BTS"]
  • bands.remove("oasis")

Remove removes the first matching value it finds, so in this example the "oasis" between "guns n roses" and "metallica". the second "oasis" would remain (as would any others later on). So the list would now be ["foo fighters","guns n roses","greenday","metallica","oasis","the cure", "one direction", "BTS"]

Del
  • bands = ["foo fighters","guns n roses","greenday","metallica","oasis","the cure", "one direction", "BTS"]
  • del bands[6]

Del deletes the value from the stated index - 6 in this case. So this would delete "one direction". Giving a list of
["foo fighters","guns n roses","greenday","metallica","oasis","the cure",  "BTS"]. Remember we count indexes from 0 and note that Del is written differently to remove and pop

Pop
  • bands = ["foo fighters","guns n roses","greenday","metallica","oasis","the cure", "BTS"]
  • bands.pop(2)

Pop is very similar to del in that it removes the value from the stated index - 2 in this case. So this would delete "greenday". Giving a list of ["foo fighters","guns n roses","metallica","oasis","the cure",  "BTS"].

Pop can tell you what it has removed though, which del doesn't. Run them in the trinket below to see how they all work

All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content