pythonpython-3.xvalueerrorraise

Can I show an index number when raising a ValueError?


I want to check the input format for a given function with a list of lists as input. I have used the code below to indicate at which index the input file has the wrong format:

for i, doc in enumerate(input_file):
    if not isinstance(doc,list):
        raise ValueError("The element of input_file at index ' + str(i) + ' is not a list")

However, the output of this code (with wrong input) is:

ValueError: The element of input_file at index ' + str(i) + ' is not a list

So, it does not convert str(i) to an actual number. Is it possible to get a number there?


Solution

  • The syntax was wrong. You have not concatenated the numbers. The code raise ValueError("The element of input_file at index ' + str(i) + ' is not a list") basically considers '+ str(i) +' as a string only.

    Try this:

    raise ValueError(f"The element of input_file at index '{i}' is not a list")