Delete a Python list element by index
Choose del, pop, or slice deletion, handle index shifts, and distinguish deleting by position from removing the first matching value.
Use del items[index] to remove an element when you do not need its value. Use items.pop(index) to remove and return it. Both change the existing list and raise IndexError if the index is out of range.
Delete one item or a slice
items = [1, 2, 3, 4, 5]
del items[2]
print(items) # [1, 2, 4, 5]
del items[1:3]
print(items) # [1, 5]
A slice selects a range with an excluded upper bound. Slice bounds are clipped, so deleting a slice beyond the end can be harmless even though deleting a single out-of-range index is an error.
Remove and return the item
items = [1, 2, 3, 4, 5]
removed = items.pop(2)
print(removed) # 3
print(items) # [1, 2, 4, 5]
Without an argument, pop() removes the last item. Negative indexes work too: del items[-1] and items.pop() remove the same position, but only pop() returns its value.
Remove by value instead
items = [1, 2, 3, 2, 4]
items.remove(2)
print(items) # [1, 3, 2, 4]
remove finds the first equal value, not an index. It raises ValueError when no matching value exists.
Avoid index shifts during iteration
Deleting while iterating forward can skip elements as later items move left. For a condition-based filter, create a new list:
items = [1, 2, 4, 5]
filtered = [item for item in items if item % 2 != 0]
To preserve the identity of the original list so other references see the change:
items[:] = [item for item in items if item % 2 != 0]
For a known collection of valid nonnegative indexes, delete unique indexes from highest to lowest. If indexes may be negative, normalize them against the original length first. Iterating over a copy and calling remove also avoids shifting the active iterator, but repeatedly searches by value.
FAQ
How can I validate an index? For an integer index i, a nonempty list accepts -len(items) <= i < len(items). Catch IndexError if concurrent changes make a prior check unreliable.
What is the cost? Removing from the middle of a CPython list shifts subsequent references. End removal is generally constant-time amortized; repeated front removal is inefficient. For queue-like workloads, collections.deque.popleft() avoids those shifts.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan