Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand cause of "IndexError: tuple index out of range" when formatting string

I looked at similar questions having this IndexError but didn't find an explanation to my case. Can someone explain why I get the error?

The following code

mySF2[0]=['000browser', '1', 'Floor', '0.92', '1.74', 'con', 'None']

insertfmt = ' '.join([
"INSERT INTO mySchema.myTable_{}_name (col1, col2, col3, col4, col5, col6)",  
"VALUES ({}, {}, NULLIF({},'None')::decimal, NULLIF({},'None')::decimal, {}, NULLIF({},'None')::int)"
         ])

insertfmt.format(mySF2[0])

Gives this error

IndexError: tuple index out of range

However, I count 7 placeholders (i.e. curly brackets {}) and 7 items to input. Why the error then?

like image 868
sc28 Avatar asked Mar 09 '17 21:03

sc28


People also ask

How do I fix IndexError tuple index out of range?

The IndexError: tuple index out of range error occurs when you try to access an item in a tuple that does not exist. To solve this problem, make sure that whenever you access an item from a tuple that the item for which you are looking exists.

What does IndexError tuple index out of range mean?

The Python "IndexError: tuple index out of range" occurs when we try to access an index that doesn't exist in a tuple. Indexes are zero-based in Python, so the index of the first item in the tuple is 0 , and the index of the last is -1 or len(my_tuple) - 1 .

How do you find the index of a tuple?

Python Tuple index() MethodPython index() method searches for the given element in a tuple and returns its position. It returns first occurrence of the element in the tuple. Index starts from 0 and end at n-1 where n is length of tuple.

What is a tuple index?

Tuple indices are used to optimize searches that have 0 or more medial-search strings and 0 or 1 final-search strings. They can also be used to optimize searches for an initial search string if no ordinary index is available over that attribute.


1 Answers

str.format() accepts a variable number of arguments corresponding to the number of "holes" in your format string. In your case, you are passing in a single argument (a list) to .format(), which causes an error because it expects seven arguments.

To pass in an array to a function as separate arguments, you need to use the * operator like so:

insertfmt.format(*mySF2[0])
like image 80
Richard Xia Avatar answered Sep 20 '22 16:09

Richard Xia