0

I am trying to create a little 'easy' script. Turns out it isn't so easy as I thought. I get this error:

IndexError: list index out of range

This here is the whole code. It happens at if name[2]: It occurs when you enter 2 words, it fully works when entering 3 though.

name = input('Enter name: ').split()
print(name)
print('Voornaam: ' + name[0])
print('Achernaam: ' + name[len(name) - 1])
if name[2]:
    print('Tussenvoegsels: ' + name[1])
print()
print('Uw volledige naam is:', end=' ')
if name[2]:
    print(name[0], name[1], name[2])
else:
    print(name[0], name[1])

Output:

>>> 
Enter name: name0 name1 name2
['name0', 'name1', 'name2']
Voornaam: name0
Achernaam: name2
Tussenvoegsels: name1

Uw volledige naam is: name0 name1 name2
>>> ================================ RESTART ================================
>>> 
Enter name: name0 name1
['name0', 'name1']
Voornaam: name0
Achernaam: name1
Traceback (most recent call last):
  File "C:/Users/lapje/Documents/Naam.py", line 5, in <module>
    if name[2]:
IndexError: list index out of range
stepper
  • 1,147
  • 2
  • 14
  • 22

3 Answers3

3

The check in if is wrong, as it doesn't make sense in the context.

Do this:

if len(name) >= 3:  #name must have at least 3 parts
    print(name[0], name[1], name[2])
else:
    print(name[0], name[1])
srbhkmr
  • 2,074
  • 1
  • 14
  • 19
1

if name[2]: doesn't check to see if name has the index [2]. It tries to access the name[2] index and evaluate the value of that index to true/false.

You need to be sure an array has an index before you try to access it or else you will get your index out of range error.

Pete Tinkler
  • 221
  • 1
  • 9
1

Easier:

x = [1, 2]
print(x[2])

You need to check whether the element exists at all and handle that case. With your code, the list could also have zero or one hundred elements. However, if you use x = split(s) to generate the list, you can also use ' '.join(x) to get back to the string (at least close to it, two consecutive spaces will be condensed to one).

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55