remove
list.clear
Removes all items from the list in place. Equivalent to `del lst[:]`; returns None.
list.clear() Parameters
| Parameter | Purpose |
|---|---|
| (no args) | clear() takes no arguments. |
| vs. lst = [] | Rebinding creates a new empty list; other names still see the old one. clear() empties the shared object. |
Examples
>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
[] Empties the list in place.
>>> a = [1, 2]; b = a
>>> a.clear()
>>> b
[] Aliases see the empty list because the same object was mutated.
>>> a = [1, 2]; b = a
>>> a = []
>>> b
[1, 2] Rebinding (a = []) does NOT clear the shared object.
>>> lst = [1, 2, 3]
>>> del lst[:]
>>> lst
[] del lst[:] is the pre-3.3 equivalent.
Gotcha
clear() mutates the shared object; `lst = []` merely rebinds the local name — a subtle difference when other references still point at the original list.
Related methods
del list[...]
Statement that deletes the element or slice at the given position, mutating the list in place. Unlike pop() it does not return the removed value; unlike remove() it targets by index, not by value.
list.pop
Removes and returns the item at position i (default -1, the last item). Raises IndexError on an empty list or an out-of-range index.
list.remove
Removes the first occurrence of a value equal to x from the list. Raises ValueError if x is not present; returns None.
← All Python list methods · Dict methods · list vs tuple vs set