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.
pop() method is declared as follows:
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 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)
View all Courses