Is there any difference between these two lines:
arr[:] = []
arr = []
I know both of them clear list.
Is there any difference between these two lines:
arr[:] = []
arr = []
I know both of them clear list.
For the second one, I think you meant arr = []
.
What that does differently is that it has arr point to a new empty list and just decrements the refcount on the existing list.
The difference is only important if something else is pointing to the original list.
>>> orig = [10, 20, 30]
>>> arr = orig # Second reference to the same list.
>>> arr[:] = [] # Clears the one list, so that arr and orig are empty
>>> orig
[]
Contrast that with:
>>> orig = [10, 20, 30]
>>> arr = orig # Second reference to the same list.
>>> arr = [] # Points arr to a new list, leaving orig unchanged
>>> orig
[10, 20, 30]