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?

2 answers

  • answered 2021-10-19 11:59 xjcl

    Use double (") instead of single quotes (')

  • answered 2021-10-19 12:01 Kris

    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")
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum