30

In a function, I want to make sure arguments a and b have the same length. I want to raise an Exception for this if not complied. I know ValueError is for exception where an argument itself doesn't conform some particular criteria. Is ValueError an appropriate error to raise in this case where criteria is between arguments? If not, any standard Python exception more appropriate?

def func(a, b):
    if len(a) != len(b):
        raise ValueError("list a and list b must have the same length")
4
  • you can simply return stating that the lists need to be the same length Commented Feb 14, 2015 at 10:35
  • 4
    Yes, I would say ValueError is the appropriate choice; your current implementation is fine. Commented Feb 14, 2015 at 10:37
  • And for those tempted to suggest using assert / AssertionError, please see stackoverflow.com/questions/944592/… Commented Feb 14, 2015 at 11:29
  • I would use IndexError Commented Feb 14, 2015 at 12:05

1 Answer 1

25

As johnrsharpe points out in the comments, ValueError is the appropriate choice.

Another contender would be IndexError, as suggested by Wikiii122. However, according to the Python docs,

exception IndexError

Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not a plain integer, TypeError is raised.)

This is likely what would be raised anyway if you didn't bother to raise an exception, but is not as descriptive as ValueError whose documention is as follows:

exception ValueError

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

Sign up to request clarification or add additional context in comments.

2 Comments

Did you mean ValueError when you typed TypeError?
@rudolfbyker: Yes, you are right! I corrected it now. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.