Issue
How can this be explained?
s = [1,2,3,4,5,6,7,8,9]
s[0] = s[0:0] #replace s[0] by empty list s[0:0]
s
[[], 2, 3, 4, 5, 6, 7, 8, 9] # s after assignment
len(s)
9
s[3] = s[0:0] # samething for s[3]
[[], 2, 3, [], 5, 6, 7, 8, 9] # s after s[3] has been replaced by s[0:0]
len(s)
9
s[5:7] = s[0:0] # replace a slice by empty list
s
[[], 2, 3, [], 5, 8, 9] # slice has been removed
len(s)
7
By following the logic from the first part where the element is replaced by an empty list and the length of the list is conserved, I can expect that each element of the slice should be replaced by an empty list.
Well, it is not! How is it explained?
Solution
When you have a single element of the list on the left-hand side, you replace that single element with whatever's on the right-hand side.
When you have a slice on the left-hand side, you replace all the elements of that slice with the elements of the list on the right-hand side. If you didn't have a list or other kind of iterable on the right side, the assignment would fail. Since the list on the right-hand side was empty, you ended up deleting the elements.
Answered By - Mark Ransom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.