PythonArraysBeginner

list.pop()

Removes and returns an item (default last) from a list (mutates).

Review the syntaxStudy the examplesOpen the coding app
item = my_list.pop(index=-1)

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Removes and returns an item (default last) from a list (mutates).

The list.pop([index]) method removes the item at the specified position in a list and returns its value. If no index is provided, pop() defaults to the last item (index -1). In terms of algorithmic complexity, popping from the end of a list is an O(1) operation, making lists efficient for stack implementations (Last-In-First-Out). However, popping from the front (index 0) or the middle is an O(n) operation because Python must shift all subsequent elements one position to the left to maintain a contiguous array. This method modifies the original list in-place and raises an IndexError if the list is empty or the index is out of bounds.

Quick reference

Syntax

item = my_list.pop(index=-1)

Inputs

Parameters

index (optional)int · Index to remove; default -1 (last).

See it in practice

Examples

1

Stack Behavior (LIFO)

stack = ['action1', 'action2', 'action3']
last_action = stack.pop()

print(last_action)
print(stack)
Output:
action3 ['action1', 'action2']

Calling pop() without arguments removes and returns the last element, mimicking a stack.

2

Removing at Specific Index

tasks = ['email', 'code', 'review', 'test']
completed = tasks.pop(1)

print(completed)
print(tasks)
Output:
code ['email', 'review', 'test']

Passing an index allows you to remove an element from a specific position. Note that items to the right of 'code' are shifted left.

3

Using the Returned Value

items = [10, 20, 30]
while items:
    current = items.pop()
    print(f'Processing {current}')
Output:
Processing 30 Processing 20 Processing 10

Since pop() returns the element, it is commonly used in loops to consume a list until it is empty.

Debug faster

Common Errors

1

IndexError

Cause: Attempting to pop from an empty list.

Fix: Check if the list is not empty before calling pop(), or use a try-except block.

data = []
if data:
    data.pop()
else:
    print('List is empty')
2

IndexError

Cause: Providing an index that exceeds the current list range.

Fix: Ensure the index is within the valid range of -len(list) to len(list) - 1.

items = ['a', 'b']
items.pop(5)  # Raises IndexError

Runtime support

Compatibility

Python 3.8+

Source: MDN Web Docs

Common questions

Frequently Asked Questions

Removes and returns an item (default last) from a list (mutates).

index: Index to remove; default -1 (last).

IndexError: Check if the list is not empty before calling pop(), or use a try-except block. IndexError: Ensure the index is within the valid range of -len(list) to len(list) - 1.