How does the pop() method work in Python lists?
a) Removes and returns the last item in the list
b) Removes and returns the first item in the list
c) Adds a new item to the start of the list
d) Clears all items from the list
Answer:
a) Removes and returns the last item in the list
Explanation:
The pop()
method in Python lists removes and returns the last item in the list by default. If you want to remove an item at a specific index, you can pass that index as an argument to the pop()
method.
# Example of pop() method
fruits = ["apple", "banana", "cherry"]
last_fruit = fruits.pop()
print(last_fruit) # Output: cherry
print(fruits) # Output: ['apple', 'banana']
In this example, the pop()
method removes the last item (“cherry”) from the list and returns it. The list fruits
is then updated to remove “cherry.”
The pop()
method is useful when you need to work with the last item in a list and also want to remove it from the list at the same time.