• pop()
  • remove()
  • del

Those are three ways to remove an item from a list in Python.

pop()

If you had a list like:

my_list = [1,4,5,9,2]

Then you ran:

my_list.pop(1)

pop will remove the item at index 1 (which is the value 4 from the list above) and return that value to you.  At the same time it removes it from the list.

So print(my_list.pop(1)) outputs 4, and if you were to print(my_list) you’ll see: [1, 5, 9, 2] as the result.

remove()

Like pop(), remove also removes an item from a list.  Unlike pop, it doesn’t return the item it removed.

So in our above example, if we did:

print(my_list.remove(1)) we would see the output of None.  Nothing is returned.

But if we did a print(my_list) we would get [1, 5, 9, 2]

del

Another way to remove a value is the del function.  Like remove it removes a value from a list without returning it.

So in our above example, if we did:

del my_list[1]

…and we did a print(my_list) we would get [1, 5, 9, 2]

Leave a Reply

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