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.
The pop()
method is declared as follows:
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.
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 listx = char_list.pop()print(x)# last element has been removedprint(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 listy = char_list.pop(2)print(y)# element at the second index has been removedprint(char_list)