Python List pop() and clear()
Core idea
items.pop() removes and returns the last item. items.pop(index) instead removes and returns the item at that index. items.clear() removes every item from the existing list and returns None. Use pop when you also need the removed value.
tickets = [21, 22, 23]next_ticket = tickets.pop(0)print(next_ticket)print(tickets)The first ticket is returned and removed. The remaining items shift left.
Reset a collection
drafts = ["A", "B"]print(drafts.pop())print(drafts.clear())print(drafts)pop returns B; clear empties the remaining list and returns None.
Empty pop: intentional error
There is no last item. A nonempty list also raises IndexError for an invalid pop index.
Common mistake
Check if items: before popping when empty input is allowed. Clearing an empty list is fine, but popping it is not.
Practice
Use pop twice on a list of three labels, print the returned values, then clear the list.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pop and clear
Check your understanding of pop and clear.
What is printed?
items = [2, 5]print(items.pop())What is printed?
items = [3, 8]items.pop(0)print(items)What is printed?
items = [2]print(items.clear())print(items)What happens if pop() is called on an empty list?