3

Given the expressions:

>>> l = [1,2,3]
>>> l[10:20] = [4,5]
>>> l
[1, 2, 3, 4, 5]

Why doesn't Python nag about the nonexistent items meant to be deleted? l.remove(55) does raise a ValueError.

Quora Feans
  • 928
  • 3
  • 10
  • 21
  • your question is not very clear. Your code is adding elements to a list, but your asking for l.remove – ljuk Jan 05 '21 at 00:29
  • @ltaljuk: yes, I asked in the assumption that slice assignments are a kind of remove+insert elements. l[0:2] = [4,5] would have removed the 1,2. – Quora Feans Jan 05 '21 at 00:34
  • Python handles slice indices gracefully, so ```"Hello World"[6:15]``` will not raise an error but just evaluate to ```"World"```. https://docs.python.org/3.0/tutorial/introduction.html : "Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string." – Christoph Jan 05 '21 at 00:39

1 Answers1

1

l.remove(55) Raises an error because you don't have the value 55 in your list.

On the other hand, l[10:20] = [4,5] is not crashing your code because that slicing method will try to add elements on those indexes, if it can't, it will be adding the new elements in the last position of your array.

Also, if you try to do (for example) l[10]=10, this will Raise the exception: IndexError: list index out of range

ljuk
  • 701
  • 3
  • 12