The list is a container data type that represents a collection of ordered elements.

Lists are mutable meaning that operations such as insertion and deletions can be performed to the list without necessarily creating another list. The pop() method is used to remove an element at a given index. If called without any argument, it simply removes the element at the end of the list.

ExampleEdit & Run
mylist = ['Python', 'Java', 'C++', 'Ruby']

#remove the last element from the list
print(mylist.pop())
print(mylist.pop())

print(mylist)
copy
Output:
Ruby C++ ['Python', 'Java'] [Finished in 0.011204294860363007s]

In the above example, we called the pop() method without any argument twice, the outcome is that the last two elements are removed from the list.

The syntax of the pop() method is as shown below;

Syntax:
lst.pop(index = -1)
copy
index Optional. The index of the element to be removed. Defaults to -1.

The  pop() method removes and returns the element at the specified index. If no index is given, the last element is removed from the list and returned.  If the index given is not valid for the list, an IndexError is raised. 

ExampleEdit & Run

without an argument

mylist = ['Python', 'Java', 'Ruby']

#remove the last element
print(mylist.pop())
print(mylist)
copy
Output:
Ruby ['Python', 'Java'] [Finished in 0.010455763898789883s]

In the following example we specify an index where the element should be removed .

ExampleEdit & Run
mylist = ['Python', 'C++', 'Java', 'Ruby']

#remove the first element
print(mylist.pop(0))

#remove the third element
print(mylist.pop(2))

print(mylist)
copy
Output:
Python Ruby ['C++', 'Java'] [Finished in 0.009927680715918541s]

Since Python also supports negative indices, we can call the pop()  method with a negative index as well.

ExampleEdit & Run
mylist = ['Java', 'Python', 'Ruby', 'PHP', 'C++']

#remove the last element
print(mylist.pop(-1))
#remove the second element from back
print(mylist.pop(-2))

print(mylist)
copy
Output:
C++ Ruby ['Java', 'Python', 'PHP'] [Finished in 0.01016559824347496s]

pop() with an invalid index

As mentioned above, an IndexError is raised if the index given is not valid.

ExampleEdit & Run
mylist = ['Python', 'Java', 'Ruby']

#an INdexError
mylist.pop(5)
copy
Output:
Traceback (most recent call last):   File "<string>", line 4, in <module> IndexError: pop index out of range [Finished in 0.009840755723416805s]