Difference between del remove and pop in Python

Introduction

In today’s Python code snippet, we are going to talk about deleting, removing and popping list elements:

  • remove method: takes a value as input, searches for it, removes the first match. If the item is not found it errors out
  • del function: removes an item at a specific index, can delete all elements or a slice
  • pop method: by default, it removes and returns the last element but you can pop any element by providing an index

Here are few examples to demonstrate that:

Examples

Removing objects

The remove method searches the list for a value (ex. integer, character, string). If the item to be removed is an object then it has to implement the equality operator so that it can be searched for. You need to add the following method to your class definition:

Running Time

Computational complexity (i.e. running time or Big-O) is as follows:

  • del O(n)
  • pop O(1)
  • remove O(n)

Note that these running times are the worst case scenarios. For example, deleting an element at the beginning of the list takes constant time.

Summary

Here is a quick summary:

Syntax
Remove item at index: mylist.remove(index)
Delete item at index: del mylist[index]
Remove and get last item: x = mylist.pop()

References

Tags:

Add a Comment

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