Python list Method - pop()

w‮gi.ww‬iftidea.com

The pop() method in Python is used to remove and return the last element from a list, or an element from a specified index. The method modifies the original list in place and returns the removed element.

The syntax for the pop() method is as follows:

list.pop(index)

Here, list refers to the list from which the element needs to be removed, and index is the optional index of the element to be removed. If index is not specified, then the last element of the list is removed.

Example:

# Creating a list
my_list = [1, 2, 3, 4]

# Removing the last element
last_element = my_list.pop()

# Displaying the modified list and the removed element
print(my_list)        # Output: [1, 2, 3]
print(last_element)   # Output: 4

# Removing the element at index 1
removed_element = my_list.pop(1)

# Displaying the modified list and the removed element
print(my_list)           # Output: [1, 3]
print(removed_element)   # Output: 2

In the above example, the pop() method is first used to remove and return the last element of the list my_list. The removed element is assigned to the variable last_element, and the modified list is printed.

Then, the pop() method is used again to remove and return the element at index 1 of the list my_list. The removed element is assigned to the variable removed_element, and the modified list is printed again.