Python - "tuple index out of range"

I am writing a program to display country information in a table format. It worked fine when I had 3 countries, but changing it to 10 (and adjusting all the necessary code accordingly), the error "Tuple index out of range" appeared 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)) 
+7
source share
2 answers

You need to pass the appropriate number of arguments for your format slots. Your format string contains 10 slots, but you only pass 3 values.

Reduced to 4 format slots with three 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 went through 4 arguments, the .format() call succeeds.

+10
source

As user jon141: I also run into this problem, and I am trying to solve this by going through one element of the column (I go through a 2-dimensional array) and then building a row based on this. So I get a string like

 template="{0!s:10}{1!s:15}...{n!s:24} 

Elements that I want to format, I put in a tuple. but when i do

 template.format(tuple_variable) 

it gives an error that the tuple index is out of range

Probably because now it passes the tuple of the tuple to a function having one element, the tuple

I have not figured out how to fix this yet, but follow thread if you need more information about this.

0
source

All Articles