Python List pop() Method - Scaler Topics (original) (raw)

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.

Example

Output:

Explanation:

Syntax of Python List pop()

The syntax of pop() in python 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,

Return Value of Python List pop()

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

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?

How to Use List pop() Method in Python?

The pop() method is a versatile and commonly used function in Python for working with lists. It allows you to remove an item from a list at a given position and return it.

Example

You have a list of numbers representing scores in a game, and you want to remove scores at specific positions or the last score added to the list:

Output

In this scenario, the pop() method is first used without specifying an index, so it removes 95, the last element in the scores list. Next, pop(2) is called, which removes the score 75 located at index 2 of the updated list. After each pop() operation, the list is updated, and the removed item is printed out.

More Examples of pop() in Python

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: Pop the Item at a Specific Index from the List

You have a list of tasks that need to be completed in a day, but you decide to remove a specific task from your list that is not at the end.

Output:

**Explanation:**In this example, we specified the index 2 in the pop() method to remove 'Lunch meeting' from the list of tasks. The pop() method not only removes the item at the specified index but also returns it, allowing you to use or store the removed item if necessary.

Example 3: Passing Invalid Index

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

Output:

Conclusion