Python List pop() Method

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Video Tutorial

List Operations

Overview

The pop() function is a pre-defined, inbuilt function in Python lists. It removes an element from the specified index. If no index is provided, then it removes the last element.

Syntax of Python List pop()

The syntax of pop() is as follows,

The list_name is the List on which the pop function will operate.

Parameters of Python List pop()

It accepts a single parameter,

  • index (optional): The pop() function accepts only one parameter: the item's index to be popped out from the list. If the index is not mentioned, it removes the last item from the list.

Return Value of Python List pop()

The pop() function returns the item, which is present at the specified index and to be removed.

Example of Python List pop()

Output:

Explanation:

  • The first pop() function call removes the last element as no index or argument is given to it.
  • The next pop() function call removes the item at index 0 as 0 is given as an argument.

What is pop() Function in Python?

The pop() function in Python is a pre-defined, inbuilt function in Python lists that removes an item at a specific index given as the argument to the pop() function. By default, it removes the last item from the list if no argument is given in its function. But if you want to remove any other item from the list, you've to mention the index as the arguments of the pop() function.

How Does pop() Function Work?

  • The pop() function expects one argument, which is the index at which the item should be removed.
  • The pop() function looks for an argument; if not provided, the index is considered as -1, i.e., the last elements from the last index are removed.
  • It returns the item removed and removes the specified item from the list.
  • If the index specified is out of the range, then the pop() function will throw an error, i.e., IndexError.

More Examples

Example 1: The pop() Function with Negative Indexes

Here we will see how the pop function works with negative indexes. Everything remains the same, and it interprets the -1 as the last index, -2 as the second last, and so on. Now you might get an idea of what is going to happen in case of a negative index. Let's discuss an example to make it clearer.

Output:

Explanation:

Functionality is working as the same, but the elements are being interpreted and accessed from the end of the list because of negative indexes.

Example 2: Passing Invalid Index

In case of any invalid(out of range) index, the pop function will raise an IndexError.

Output:

Conclusion

  • The pop() function is widely used in Python lists to remove an item from the list.
  • It is mainly used to remove the last item as you need to simply do list_name.pop().
  • It works with negative indexes as well.