Why didn't this give an error?

Okay so I know it’s a little odd trying to understand why something didn’t give an error but if I am going to truly understand my code I feel like I should know why.

Here is the code:

string = ABCDCDC
sub_string = CDC

lst = [string[i:i+len(sub_string)] for i in range(len(string))]
print(lst.count(sub_string))

The objective is to see how many times the sub_string appears in the given string and this code actually works perfectly. I am wondering, however, why it doesn’t give an ‘Index is out of range’ error message.

If I follow through the code in my head at some point ‘i’ should be equal to the end of range(len(string)), in this case it would be 6. Then if you perform the string[i+len(sub_string)] in this case it should be string[6:9]. 9 is obviously not an index in the string given here.

If I were to print(lst) I would get: [‘ABC’, ‘BCD’, ‘CDC’, ‘DCD’, ‘CDC’, ‘DC’, ‘C’]

What gives? Why does this work?

Short answer: when using slice, if either the start or stop value are greater than the length of the list, the length of the list is used instead. See the docs for more information (note 4.).

1 Like