Python Tutorial
Python Remove List Items
remove() deletes by value, pop() by index, del by index or the whole list, clear() empties it.
remove() and pop()
remove() deletes the first matching value. pop() returns the removed item (last if no index).
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
item = thislist.pop(0)
print(item, thislist)del and clear()
del can remove one item or the list itself. clear() leaves an empty list.
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
thislist.clear()
print(thislist)📘 Real-World Deep Dive
Removing items correctly — by value, by index, in bulk — without leaving partial state is the operation you most often get wrong. Knowing the four ways (<code>remove/pop/del/clear/comprehension</code>) keeps code sane.
Real-Life Scenario
Strip out invalid records ("", <code>None</code>, NaN-like) from a stream of sensor readings, then verify the post-condition count.
Real-Life Example
import math
raw = [
{"id": 1, "temp": 22.4},
{"id": 2, "temp": None},
{"id": 3, "temp": float("nan")},
{"id": 4, "temp": 0},
{"id": 5, "temp": ""},
{"id": 6, "temp": 24.7},
]
def is_valid(r: dict) -> bool:
t = r["temp"]
if t is None or t == "": return False
if isinstance(t, float) and math.isnan(t): return False
return True
# in-place cleanup using slice-assignment
clean = [r for r in raw if is_valid(r)]
# alternatively, in-place
raw[:] = [r for r in raw if is_valid(r)]
print("clean:", clean)
print("len :", len(clean))
print("ids :", [r["id"] for r in clean])Expected Output
clean: [{'id': 1, 'temp': 22.4}, {'id': 4, 'temp': 0}, {'id': 6, 'temp': 24.7}]
len : 3
ids : [1, 4, 6]Common mistakes
list.remove(value)raisesValueErrorif absent; usetry/exceptor filter via comprehension.del xs[i]shifts elements;xs[i:i+1] = []is another in-place form.- Mutating a list while iterating it skips elements; iterate a copy or build a new list.
🚀 Performance & Best Practices
- Comprehension-and-rebind is fast and Pythonic;
.remove()in a loop is O(n²). - For huge arrays of numbers,
numpymasking is dramatically faster than Python filtering. - Always
len()the list after filtering if your code depends on the exact count.
🧪 Try It Yourself
- Write
drop(xs, predicate)that removes elements respecting the predicate. - Use
numpyto filter 1 M rows wheretempis finite and positive. - Profile
xs[:] = [..]vs.xs.clear(); xs.extend([..]).