CodeMonkey CodeMonkey - 3 months ago 7
Python Question

Why does my nested loop throw an exception in Python?

This is a simple code,

def door_traversal():
arr = []
for i in range(1, 101, 1):
arr.append(0)
for i in range(1, 101, 1):
for j in range(i, 101, i):
arr[j] = not arr[j]

count = 0
for i in range(1, 101, 1):
if arr[i] == 1:
count += 1
return count


I get the following error,

arr[j] = not arr[j]
IndexError: list index out of range


When I run the code in the debugger, I see that after executing the inner loop for the first time the program counter skips, it's never running the inner loop 100 times.
I'm new to Python, any help appreciated.

NPE NPE
Answer

Python list indices always start from zero. Thus, the following creates a list containing 100 elements, with indices from 0 to 99 (not from 1 to 100 as you might be expecting):

for i in range(1, 101, 1):
    arr.append(0)

Now, the following can try to access the element at index 100, which does not exist:

for i in range(1, 101, 1):
    for j in range(i, 101, i):
        arr[j] = not arr[j]

Hence the exception.