Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

for loop is not iterating correctly

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

It should be:

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading