Python Reference ยท Lists, Tuples and Ranges
Python list.clear() method
Reference for Python list.clear(): remove every item from a list in place, how it differs from assigning an empty list, and equivalents like del lst[:].
The clear() method removes every item from a list, leaving it empty. It works in place on the same list object and returns None. Added in Python 3.3, it matches dict.clear() and set.clear().
The important detail is that clear() empties the existing object, while items = [] makes the name point at a brand-new list. Other references to the old list see the difference.
items = [1, 2, 3] items.clear() print(items) # []
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list.clear()
This method takes no parameters.
Return value: None.
Raises: nothing. Clearing an empty list is allowed.
Usage notes
- In place. Every variable that references the list sees it become empty. That is exactly what you want when a function or object shares a list with other code.
- Rebinding is different.
items = []leaves the old list untouched for anyone else holding it. Pickclear()when the identity of the list matters, and= []when you simply want a fresh one. - Shallow effect. The items themselves are not destroyed, only released. If they are referenced elsewhere they live on. A copy made earlier with
copy()is unaffected. - Equivalents.
del items[:]anditems[:] = []do the same thing and work in code that must also run on very old Pythons.clear()reads best. - Returns
None. Do not writeitems = items.clear(), which replaces the list withNone. - Do not clear while iterating over the same list unless you are leaving the loop immediately.
- Memory. CPython releases the element storage when a list is cleared, so a cleared list takes very little space.
Related
list.copy(),list.pop(),list.remove(),list.append(),list- Lessons: Lists, List methods