Last active
October 30, 2015 18:22
-
-
Save yarko/02f24c35341885791398 to your computer and use it in GitHub Desktop.
Clear List (python) - the confusion of slice-assignment vs. slice selection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def clear(alist): | |
'''clear(alist) | |
when you want the contents of a list cleared, | |
so that all references to that list are affected. | |
python3 has a clear() method on lists; | |
there are at least 3 other ways to accomplish the same, | |
two of them syntactically tricky, and obscure. | |
The trickiness is slice notation: | |
- if on lhs of expression, slice assignment calls | |
the class's __setitem__ and does iteration in | |
the background; | |
- if on rhs of expression, a copy of the slice is returned; | |
These are very different operations for the same notation. | |
This function encapsulates that trickiness. | |
Here are the ways: | |
del alist[:] | |
- uses slice assignment to clear the list | |
- fastest: {python2.7.10: ~60ns; python3.5: ~85ns} | |
- see https://docs.python.org/2/tutorial/datastructures.html#the-del-statement | |
alist[:] = [] | |
- slice assignment; | |
- {python2: ~90ns; python3: ~110ns} | |
while len(alist) > 0: alist.pop() | |
- explicitly clears list's contents | |
- syntactically as clear as python3's alist.clear() | |
- ~120ns in either python | |
alist.clear() | |
- python3 only: ~95ns | |
using this function: | |
clear(alist) | |
- ~180ns | |
the 'del' form is fastest, if most syntactically obscure. | |
we'll use that here | |
''' | |
del alist[:] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment