1

I keep getting Index Errors when I try to use while loops in combination with lists.

I wrote the code some time ago, came back to it, but just couldn't wrap my head around it enough to find my mistake. Apparently, the error has something to do with my lists indexes being too small or too large.

indexes = []
#Or indexes[0], but this threw another error
indexes.append(decoded.find(special_string))

x=1
while indexes[x-1] > 0:
    total = sum(indexes)
    indexes[x] = decoded.find(special_string, total)
    x+=1

print(indexes)

My goal is to find all substrings (special_string) in a string and get their indexes (please inform me if you know an easier way to do this). I want to write all indexes out into a list for further use.

3
  • I wanted to declare indexes[1] to decoded.find(node_identifier, total) so that it ignores the first special_string and gives me the location of the next one. Commented Jun 17, 2019 at 16:07
  • Why are you tring to sum the indexes? Also, that kind of approach will ALWAYS result in list index out of range, because you're trying to index a list without checking for its size. Commented Jun 17, 2019 at 16:07
  • I am trying to sum it up in order to know how many characters I already iterated through. Commented Jun 17, 2019 at 16:15

1 Answer 1

2

I think the only change you need to make is from:

indexes[x] = decoded.find(special_string, total) to:

indexes.append(decoded.find(special_string, total))

You can't assign indexes[x] since it doesn't exist.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer! I will accept it as soon as possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.