Problem scenario
You want to know how remove
is different from pop
when manipulating a list in Python. What should you do?
Solution
Here are four facts which should help elucidate the differences.
- The
remove
keyword searches for a matching item in the list -- not by its indexed, integer value; then the first matching item is removed. (We tested it. You may want to see this external page.) - Remove does not return a value.
- Pop removes an item based on its indexed, integer value.
- Pop returns the item removed.
Here are two programs which help display the the details of what is happening behind-the-scenes.
This program involves four function calls:
import cProfile
a = "z", "y", "x", "w", "v"
contintlist = list(a)
cProfile.run('contintlist.remove("z")')
# One function call is finding the matching element in the list. The second is removing the first match.
This program also involves four function calls:
import cProfile
a = 1, 2, 3, 4, 5
contintlist = list(a)
cProfile.run('contintlist.pop(3)')
# One function call is removing the item in the list. The second is returning that item.