My function splits a string to lines, checks the index-th line, and returns one of two values. Here’s a simplified version:
def f(text, index):
rows = text.split('\n')
row = rows[index] # <-- IndexError thrown here.
if row_meets_some_condition:
return "Yes"
else:
return "No"
The caller sometimes passes a negative value for index (when he wants to use end-of-file-based-indexing), which works fine, unless text haw too few lines, in which case I get an IndexError at the row = rows[index] line.
Is there an idiomatic way to check that index is a legal index into rows, other than catching the error?
Catching an
IndexErroris pretty idiomatic in Python. If you cannot foresee how many lines your input has, you can either check the length ofrowsbefore accessing the list or just catch theIndexError. I’d go for the second option then.