list.clear()
Empties the list itself rather than rebinding the name. Everyone else holding the same list sees it empty too — which is the point, and the trap.
Demo
The demo output is None, and that is the real return value — clear mutates the list and gives nothing back. The effect you care about is invisible in the result: every element is removed from the EXISTING list object rather than a new empty one being made, so the list keeps its identity and every other reference to it sees the change. Clearing an already-empty list is a no-op and never raises.
Common patterns
for batch in batches: buffer.clear() buffer.extend(process(batch))
self.pending.clear() # every reader of self.pending sees empty
state.errors.clear()
Examples
Pitfalls
a = [1, 2] b = a a = [] b
a = [1, 2] b = a a.clear() b
xs = [1, 2] xs = xs.clear() print(xs)
xs.clear()
xs = [1, 2, 3] for x in xs: xs.clear() print(x)
for x in xs: print(x) xs.clear()
xs.clear()
del xs[:]
When to use
- Emptying a list other code also holds a reference to
- Reusing one buffer across iterations instead of reallocating
- Resetting a list attribute without rebinding it
- You want a fresh, independent list → xs = []
- Removing only some items → a comprehension or filter
- Removing one item → remove or pop
Notes
FAQ
clear empties the existing list object; xs = [] points the name xs at a brand new one. If anything else refers to the original — another variable, an attribute, a list of lists — clear affects it and rebinding does not.
a = [1, 2] b = a a.clear() b # [] a = [1, 2] b = a a = [] b # [1, 2]