-3

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?

Whymarrh
  • 13,139
  • 14
  • 57
  • 108
flamenco
  • 2,702
  • 5
  • 30
  • 46
  • "I can expect that each element of the slice should be replaced by an empty list" - slice assignment doesn't operate elementwise. – user2357112 May 20 '14 at 00:38

3 Answers3

2

It's not true that the length of the list is always conserved. What is true is that the slice on the left is replaced with whatever is found on the right.

lst = [0, 1, 2, 3, 4, 5, 6, 7]

print(lst[0]) # prints one value
print(lst[3]) # prints one value
print(len(lst[1:3])) # prints 2, length of sublist
print(len(lst[:])) # prints 4, length of whole list

lst[:] = []  # replace entire list with empty list

By the way it is very weird to use the slice [0:0] to get a zero-length list. Easier to understand if the code just put [], the literal that represents a zero-length list.

steveha
  • 74,789
  • 21
  • 92
  • 117
2
s[3] = s[0:0]   # replacing single element
s[5:7] = s[0:0] # replacing two elements and setting to []  removes the elements.
using s[5] = s[0:0],s[6] = s[0:0] is different from s[5:7]

If you change s[5:7] = s[0:0] to s[5:7] = s[0:2], you will get different behaviour, both will be changed.

If you use s[5:7] = s[0:1]the element at index 5 will be changed and the element at index 6 will be removed.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2

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.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622