0
# Attempt1 using direct index-based assignment
p=[1,2,3,4]
p[1]=p[2]=[]
print(p) # [1, [], [], 4] 
// that sounds reasonable..


# Attempt2 using slice-based assignment
p=[1,2,3,4]
print(p[1:3]) # [2, 3]
p[1:3]=[] 
print(p) # [1, 4] !!

In my understanding after reading the answers from here, p[1:3] is supposed to be a sequence of references on which the assignment to an empty list is supposed to happen. But it seems to remove the elements from the list ! Almost as if, I did this:

p=[1,2,3,4]
print(p) # [1, 2, 3, 4]
del p[1:3]
print(p) # [1, 4]

Can you explain this ?

2020
  • 2,821
  • 2
  • 23
  • 40
  • 1
    You assign a slice a list to a certain slice of a list. You can for example assign a list containing more elements to extend the list. In essence it boils down to the fact that the list after modificationis `oldlist[:begin] + value + oldlist[end:]` with `begin` and `end` the begin and end parts of the slice respectively. – Willem Van Onsem Jun 28 '19 at 22:31

1 Answers1

1

When you assign a slice, it performs element-by-element assignment between the two lists. So if you do:

list1[1:3] = [1, 2]

it's roughly equivalent to:

list1[1] = 1
list1[2] = 2

But this is only the case when the slice is the same length as the source list.

If the source list is shorter, it deletes any extra elements in the destination slice. And if the source list is longer, it inserts the extra elements at the end of the slice.

So if the source list is empty, as in your code, all the elements of the slice are "extra", so the slice is deleted from the list.

Barmar
  • 741,623
  • 53
  • 500
  • 612