Python pop() Function | First, by value, pop multiple Examples

Python pop function is used to remove a returns last object from the list. You can also remove the element at the specified position using pop() function by passing index value.

Note: If the index is not given, then the last element is popped out and removed from the list.

Syntax

Remove and return last time

Remove the element at the specified position

Parameters

Index of the object to be removed from the list. (optional)

Return Value

The pop() method returns removed value.

Python pop function Examples

Let’s see multiple example for better understandings.

1. Without parameter (no index value)

If you don’t pass the parameter in the pop() method, it will remove and return the last value of the list.

Output:

Kotlin
[‘Python’, ‘Java’, ‘C++’]

2. With Parameter – Remove a specific item by index

You can remove a element specified position using index value in pop() function, see below example to remove ‘java’ value.

Note: list indexing is start from 0.

Output:

Java
[‘Python’, ‘C++’, ‘Kotlin’]

3. Negative indices

What will happen if we pass the negative value in pop() function.

It will work fine, no error. Will remove last item if pass “-1”, second last will remove if pass “-2” and so on in circular way.

Q: How to Python list pop first?

Answer: To remove the first element from a list you have to just pass the index value 0 into a pop function.

Output:

1
[4, 3, 6, 7]

Q: How to the Python list pop multiple elements?

Answer: You can use a list comprehension to rebuild the list:

Source: https://stackoverflow.com/

Output:

[4, 6, 7]
[1, 4, 3, 6, 7]

Q: How to Python list remove item?

Answer: List have many method to remove elements from list, like – Pop() and remove() method

Read this tutorial:- Python list remove() function to remove elements by value.

Do comment if you have any doubts and suggestions on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.