AMM
AMM

Reputation: 196

String index out of range: IndexError

Don't understand why am I getting index out of range... tried finding the mistake with: http://pythontutor.com/visualize.html#mode=display

It "updates" the i and l, but I get the error even without finishing the word.

What I'm trying is to print every name that has an space no farther than its 5th character, so my expected output would be:

Rama as
Nemo as

Code:

spaceNames = ['Rama as', 'Nemo as', 'Siegss as', 'Kama', 'Gray', 'BB', 'BB']

for name in spaceNames:
    i=0
    for l in name:
        
        if i <= 4 and l[i] == " ":
          print(name)
        print(i)
        i+=1

Any help appreciated!

Upvotes: 0

Views: 70

Answers (3)

Ben Y
Ben Y

Reputation: 1023

There seems to be a lot of looping when you can just get most of the conditions you were looking for more efficiently.

spaceNames = ['Rama as', 'Nemo as', 'Siegss as', 'Kama', 'Gray', 'BB', 'BB']

for name in spaceNames:
    idx = name.find(' ')  # This returns -1 if no space
    if idx < 0 or idx > 4:
        continue  # Skip
    print(name)

Upvotes: 0

AMM
AMM

Reputation: 196

Figured out how to solve with both comments you guys did:

spaceNames = ['Rama as', 'Nemo as', 'Siegss as', 'Kama', 'Gray', 'BB', 'BB']

for name in spaceNames:
    i=0
    for l in name:
        if name.index(l) <=4 and name[i] == " ":
            print(name)
        i+=1

Thanks!

Upvotes: 0

Prune
Prune

Reputation: 77857

A trivial trace of your program, or even an eyeball check, reveals that l is a single character. You're using indices up to 3. A single character has only l[0] as a legal reference.

We have no way to "fix" your program, as we have little idea what you're trying to do.

Upvotes: 1

Related Questions