Python list pop function | Remove element from the list

Python list pop function is used to removes the element at the given index from the list and it returns the removed item. So basically you can remove the element at the specified position by using the pop() Method in Python List.

Note: Index in Python List starts from 0, not 1.

Syntax

Parameter

index (optional) – The value at index is popped out and removed from the list. It takes a single argument.

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

Returns

It returns the item present at the given index. 

Examples of Python list pop

1. Pop item at the given index from the list

List indexing is started from 0, so if you want to remove first element form list then you have to pass the 0, for 2 element pass 1…

In the example deleting a 2 value, So you have to pass index value 1.

Output:

Return Value: Java
List after removed item: [‘Python’, ‘C++’, ‘French’, ‘C’]

2. Python pop “First Element” from the list

To delete first element from list you have to just pass the 0 index value in pop() method.

Python pop Number and String from the list the same way, just need to pass index value.

Output:

Return Value: A
Updated list: [‘B’, ‘C’, ‘D’, ‘E’]

3. Python list pop last

list.pop() removes and returns the last element of the list. You don’t need to pass any value to delete the last value of the list in pop() function.

Output:

6
New List: [1, 2, 3, 4, 5]

IndexError: pop index out of range

Example of Python3 program for error in pop() method.

Output:

Python list pop function Remove element

Q: How to Python pop multiple values?

Answer: Using a Using list comprehension, you can remove multiple values from list.

Note: It’s removed by value not index and we are using a Python remove function.

Output:

Updated list: [10, 5, 18, 50]

Q: How to Python list pop by value?

Answer: You can use remove() functionto removes the first matching value, not a specific index.

Output:

Updated list: [10, 5, 18, 43, 50]

Do comment if you have doubts and suggestions on this topic.

Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python Programs code are in Python 3, so it may change 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.