Atropos Atropos - 2 months ago 11
Python Question

Understanding index out of range Python

Hello thanks in advance.

i can get my code to work but i need help understanding what the problem is.

i am doing a test questions on codingbat and came across this one.

Return the number of times that the string "code" appears anywhere in the given string, accept any letter for the 'd', so "cope" and "cooe" count.


count_code('aaacodebbb') → 1 count_code('codexxcode') → 2
count_code('cozexxcope') → 2


now after a few tries i got my code to work


def count_code(str):
count =0
for i in range(len(str)):
if str[i:i+2] == 'co' and str[i+3:i+4]=='e':
count += 1
return count
print(count_code('codecodecode'))



^ I understand this (and I could have done regular expressions but i can not import)

But my first attempt was this:


def count_code(str):
count =0
for i in range(len(str)):
if str[i:i+2] == 'co' and str[i+3]=='e':
count += 1
return count
print(count_code('codecodecode'))



the browser (the browser saves, compiles, and runs) gave me an index out of range error and after testing i understand why. when i = 9 ... i +9 = 12 which is longer than the string so out of range i get it. But i ran the 2nd code in Aptana and it worked fine so is the second bad code or not?

but the code that works containing str[i+3:i+4] == 'e' does not go out of range and i do not understand why. when i reaches counter 9 then it would be str[12:13] which is longer than the string.

thanks for the help still learning basics and want to make sure i have a good foundation.

Answer

When you say mystring[x:y], that is called slicing, which has built-in bounds checking.

But a plain list index such as mystring[99] does not have built-in bounds checking, so you get an IndexError.

Comments