Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - "tuple index out of range"

I am writing a program to display information about countries in a table format. It worked perfectly fine when I had 3 countries, but changing it to 10 (and adjusting all necessary code accordingly) resulted in the error, "Tuple index out of range" in the line:

print("{0:^20}{1:^20}{2:^20}{3:^20}{4:^20}{5:^20}[6:^20}{7:^20}{8:^20}{9:^20}".format(newcountrylist[i].country,newcountrylist[i].currency,newcountrylist[i].exchange))
like image 420
keirbtre Avatar asked Dec 16 '12 16:12

keirbtre


1 Answers

You need to pass in a matching number of arguments for your format slots. Your format string has 10 slots, but you are only passing in 3 values.

Reduced to 4 format slots, with only 3 arguments to .format(), shows the same error:

>>> '{0:^20}{1:^20}{2:^20}{3:^20}'.format(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> '{0:^20}{1:^20}{2:^20}{3:^20}'.format(1, 2, 3, 4)
'         1                   2                   3                   4          '

When I passed in 4 arguments the .format() call succeeds.

like image 59
Martijn Pieters Avatar answered Sep 21 '22 22:09

Martijn Pieters