What is the pythonic way for checking a user provided vector index?
def get_value(vector, index):
try:
return vector[index]
except IndexError:
raise ValueError('bad index')
or
def get_value(vector, index):
if -1 < index < len(vector):
return vector[index]
else:
raise ValueError('bad index')
Trying first is more Pythonic. From the glossary:
Although I wouldn’t even put that around a
try…exceptsince you’re just throwing an IndexError, which it already does.