Skip to content

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

  • by

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 the pop() function by passing the 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

list.pop(index)

Remove the element at the specified position

list.pop(index)

Parameters

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

Return Value

The pop() the method returns the removed value.

Python pop function Examples

Let’s see multiple examples for better understandings.

1. Without parameter (no index value)

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

languages = ['Python', 'Java', 'C++', 'Kotlin']

print(languages.pop())
print(languages)

Output:

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

2. With Parameter – Remove a specific item by index

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

Note: list indexing starts from 0.

languages = ['Python', 'Java', 'C++', 'Kotlin']

# removing java
print(languages.pop(1))
print(languages)

Output:

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

3. Negative indices

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

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

languages = ['Python', 'Java', 'C++', 'Kotlin']

# Negative value
print(languages.pop(-1))
print(languages)

Q: How to Python list pop first?

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

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

# Remove first value
print(list1.pop(0))
print(list1)

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:

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

# Remove
indices = {0, 2}

print([v for i, v in enumerate(list1) if i not in indices])


Source: https://stackoverflow.com/

Output:

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

Q: How to Python list remove item?

Answer: List has many method to remove elements from a 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading