In Python How Is the List Function “remove” Different from “pop”?

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.

  1. 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.)
  2. Remove does not return a value.
  3. Pop removes an item based on its indexed, integer value.
  4. 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.

Leave a comment

Your email address will not be published. Required fields are marked *