Christian Singer
Christian Singer

Reputation: 305

IndexError: list index out of range

I'm using Python 3.5, 32-bit on Windows 10.

While I am aware that questions regarding this error message have been asked and answered frequently, I still can`t figure out why my code or the corresponding .txt file actually cause this error.

The code is a 1:1 copy from a Python beginner book and a derivative of this code where I only changed the name of the dictionary and used another .txt file worked fine.

Here is the code:

woerter={}
fobj=open("Woerterbuch.txt","r")
for line in fobj:
   zuordnung=line.split(" ")
   woerter[zuordnung[0]] = zuordnung[1]
fobj.close()

print(woerter)

And here is the corresponding .txt file:

Spain Spanien
Germany Deutschland
Sweden Schweden
France Frankreich
Italy Italien

The code will produce the following error:

    Traceback (most recent call last):
      File "C:\Users\Christian\Desktop\Python-Programme\Dateiausleseprogramm2.py", line 5, in <module>
        woerter[zuordnung[0]] = zuordnung[1]
    IndexError: list index out of range

Upvotes: 1

Views: 10187

Answers (1)

Prune
Prune

Reputation: 77857

Your given code and file do not reproduce the error. However, if I add another line feed (empty line) to the file, that produces the error you give. I removed the leading blanks in both files, and added a couple of tracing print statements to your code:

woerter={}
fobj=open("Woerterbuch.txt","r")
for line in fobj:
   zuordnung=line.split(" ")
   woerter[zuordnung[0]] = zuordnung[1]
   print (zuordnung)
fobj.close()

print(fobj)
print(woerter)

Without the blank line at the end of the input file, get the output I wanted:

['Spain', 'Spanien\n']
['Germany', 'Deutschland\n']
['Sweden', 'Schweden\n']
['France', 'Frankreich\n']
['Italy', 'Italien\n']
<_io.TextIOWrapper name='so.txt' mode='r' encoding='UTF-8'>
{'Germany': 'Deutschland\n', 'Sweden': 'Schweden\n', 'Italy': 'Italien\n', 'Spain': 'Spanien\n', 'France': 'Frankreich\n'}

With the blank line, I can reproduce your problem. The print statements make the immediate cause to be obvious:

['Spain', 'Spanien\n']
['Germany', 'Deutschland\n']
['Sweden', 'Schweden\n']
['France', 'Frankreich\n']
['Italy', 'Italien\n']
['\n']
Traceback (most recent call last):
  File "so.py", line 6, in <module>
    woerter[zuordnung[0]] = zuordnung[1]
IndexError: list index out of range

Note that I removed leading blanks from the data file you posted: these make the first split to be '' always, with two more fields following.

Upvotes: 1

Related Questions