for loop is not iterating correctly

Question:

I tried to iterate through this list and append the indexes of the parenthases, but it gave the wrong ones back.

Code:

t = "(= 2 (+ 4 5))"
a = []
for each in t:
        if (each == '(') or (each == ')'):
            a.append(t.index(each))
        else:
            pass
print(t)
print(a)

Result:

(= 2 (+ 4 5))
[0, 0, 11, 11]

It should be:

(= 2 (+ 4 5))
[0, 5, 11, 12]
Asked By: Adras Baros

||

Answers:

You can avoid making python search back through a list (You have t.index(each)) by using enumerate() to get the index directly:

t = "(= 2 (+ 4 5))"
a = []
for index,each in enumerate(t):
        if (each == '(') or (each == ')'):
            a.append(index)
        else:
            pass
print(t)
print(a)

Output as requested

Answered By: quamrana

In the condition of ‘if’, there is a space between ‘==’ and ‘(‘. you should delete it. Write " if (each =='(‘) or (each ==’)’) " instead of "if (each == ‘(‘) or (each == ‘)’)".

Answered By: nafiseh rahmani
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.