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.

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

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

print(mylist)

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;

lst.pop(index = -1)
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. 

without an argument

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

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

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

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

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

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

print(mylist)

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

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)

pop() with an invalid index

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

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

#an INdexError
mylist.pop(5)