What is the difference between those lines?
>>> my_list = []
>>> my_list[:] = []
>>> my_list[:][:] = []
>>> my_list[:][:][:] = []
>>> my_list[:][:][:][:] = []
>>> my_list[:][:][:][:]... = []
What is the difference between those lines?
>>> my_list = []
>>> my_list[:] = []
>>> my_list[:][:] = []
>>> my_list[:][:][:] = []
>>> my_list[:][:][:][:] = []
>>> my_list[:][:][:][:]... = []
my_list = []
creates a new list object and binds the name my_list
to it. If anything was bound to my_list
before that reference is now gone.
my_list[:] = []
requires my_list
to already be bound to a list object (or other type that supports slice assignment); all indices contained in that list object are replaced by the indices in the other list object on the right-hand-side. In this case both lists are empty, so there is no actual change, but if my_list
had any contents they would have been cleared now.
my_list[:][:] = []
first selects a slice from the existing my_list
object, producing a new list object, then applies step 2 to that result. The new list object is then discarded again.
The rest are just variants of 3, with the selection being applied multiple times.
To illustrate, change what is contained in my_list
. First step 1:
>>> my_list = [1, 2, 3]
>>> other_reference = my_list
>>> other_reference is my_list
True
>>> my_list = ['new', 'list']
>>> my_list is other_reference
False
>>> other_reference
[1, 2, 3]
The my_list
name was bound to a new list object, the list object itself, still referenced by other_reference
was unchanged.
Step 2 changes the list object itself:
>>> my_list = [1, 2, 3]
>>> other_reference = my_list
>>> my_list[:] = [4, 5]
>>> my_list is other_reference
True
>>> other_reference
[4, 5]
>>> my_list
[4, 5]
All indices in the list object were replaced, and other references to the same list object see the change.
Step 3 makes no changes, as a copy is altered instead:
>>> my_list = [1, 2, 3]
>>> other_reference = my_list
>>> my_list[:][:] = [4, 5]
>>> my_list is other_reference
True
>>> my_list
[1, 2, 3]
>>> my_list[:][:][:] = ["won't", 'matter']
>>> my_list
[1, 2, 3]