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?
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.
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 .
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.
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With