본문 바로가기

Language/Python

[Error] Why does substring slicing with index out of range work?

Question : Why doesn't example[999:9999] result in error? Since example[999] does, what is the motivation behind it?

 

Answer : 

  • [999:9999] isn't an index, it's a slice, and has different semantics. From the python intro : "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"
  • The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s).

 

Source :