0

While reading about slicing in Python I came across this interesting example which doesn't make sense. let a be a list

 a = [1,2,3,4,5,6,7]
 a[1:4] = [0,0]
 print(a) 
 output>> [1, 0, 0, 5, 6, 7]

 a = [1,2,3,4,5,6,7]
 a[1:6:2] = [0,0]
 ValueError: attempt to assign sequence of size 2 to extended slice of size 3

Why do we get ValueError in the second case? The description says size 2 to extended slice of size 3 but in first case we are assigning the sequence of size 2 to a slice of size 3 and it works.

2ank3th
  • 2,948
  • 2
  • 21
  • 35
  • @JBernardo Actually, I don't think this is a good duplicate target, although I'm certain I've seen this question before, but I can't find an appropriate target. This is asking specifically about the case where you use list assignment on a degenerate slice, i.e. start and stop are equal. Indeed, the answers in that target barely mention slice assignment. – juanpa.arrivillaga Jun 22 '17 at 19:13
  • I don't think this is really a duplicate of the referenced question. This isn't asking for a tutorial on slicing, but about one corner case, which isn't covered in the referenced question. – OldGeeksGuide Jun 22 '17 at 19:13
  • 1
    You can find the answer to your updated question [here](https://docs.python.org/2.3/whatsnew/section-slices.html). – glibdud Jun 22 '17 at 19:17
  • I changed the duplicate target. In particular, you should pay attention to [this](https://stackoverflow.com/a/10623383/5014455) answer. Probably, the easiest way of thinking about this degenerate case is as an "insert/extend". – juanpa.arrivillaga Jun 22 '17 at 19:19
  • 1
    Remember that slices point to the spaces between elements, thus 4:4, while it doesn't contain anything, points to the space between 4 and 5. When you assign it, it sticks it there. If you have a non-empty slice, it will replace the elements in that slice with what you're assigning. In this case, there are no elements to replace, so it just adds the elements in at the appropriate place. – OldGeeksGuide Jun 22 '17 at 19:20
  • I think the question changed since I first looked at it, so my previous comment no longer applies. – OldGeeksGuide Jun 22 '17 at 19:22

0 Answers0