Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How does pop() list work in Python?

Mahnoor Zaheer

The pop() method is a list function in Python that either removes the last element of the list or the value at the specified location if the index is given.

Syntax

The pop() method is declared as follows:

The syntax of the pop() method in Python

Parameters and return value

The pop() function does not take any mandatory parameters. However, it may have an optional argument. This parameter indicates the index from which the element has to be popped off. If no argument is passed into the pop() method, it removes the last element of the list.

This function returns the element that has been eliminated from the list.

Code

In the code below, the pop() function removes the last element from “char_list” because no index has been specified.

char_list = ["a", "b", "c", "d", "e"]

# removes the last element of the list
x = char_list.pop() 
print(x)

# last element has been removed
print(char_list)

On the other hand, in the given example, the index is specified in the pop() method, so it removes the element “c” that is present at the second index of the list.

char_list = ["a", "b", "c", "d", "e"]

# removes the element at second index from the list
y = char_list.pop(2) 
print(y)

# element at the second index has been removed
print(char_list)

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring