user3199813
user3199813

Reputation: 11

Why is this out of bounds? python

Enter expression:car.a + var.a
car   Variable
.   Variable
a   Variable
+   operator
var   Variable
.   Variable
a   Variable
Traceback (most recent call last):
  File "D:\My Documents\Python\Lexical analyzer.py", line 62, in <module>
    if(check_main(temp[i]) == 'Variable'):
IndexError: list index out of range

for i in range(1,len(temp),2):
if temp[i] == '.':
    if check_main(temp[i-1])=='Variable':
        temp[i-1:i+2]= [''.join(temp[i-1:i+2])]

The list was correct ['car.a', '+', 'var.a'] but i don't know why it showed an out of bounds,sorry for my bad english

Upvotes: 0

Views: 211

Answers (1)

aIKid
aIKid

Reputation: 28242

It's out of bonds because you're modifying the list while iterating over its length. The problem is with this line:

temp[i-1:i+2]= [''.join(temp[i-1:i+2])] 

Here, you changed what once was three items to only one item. So as you iterate over it, the length of your list actually shortens! Quite strange, huh? At one point, temp[i] will be no longer valid, since i is already bigger than the current len(temp).

You're encountering something like this:

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

Solution? Instead of modifying the list, i'd recommend you to make a new one. Maybe something like this:

if check_main(temp[i-1])=='Variable':
    new_list.append(''.join(temp[i-1:i+2]))

Hope this helps!

Upvotes: 7

Related Questions