loop
Lists and list processing

Module 3 · Lists and list processing · Lesson 5 of 7

Removing elements

Lists shrink, too — and crucially, they never leave a hole. Remove an element and everything after it slides left to close the gap, the exact mirror image of an insert. There are three ways to do it, each for a slightly different situation.

del nums[1]
10152030

pop() does the same to the last element — but hands the value back to you on the way out.

del nums[1] removes whatever is at index 1. nums.pop() removes the last element — but also returns it, so you can use the value you just took out (pop an index, like pop(0), to take from elsewhere). And nums.remove(20) deletes the first element that equals a value, when you know the value but not the position.

Run it yourselfruns in your browser · Python
main.py

A couple of gotchas: remove() only takes out the first match, and asking it to remove something that isn't there raises a ValueError. When in doubt, value in nums first.