Python: how to get error from list[-1]? -
is there way return error index value [-1]?
>>>l=[1,2,3] >>>l[-1] error:list index out of range
not built-in list type, can define own class has stricter indexing rules:
>>> class strictlist(list): ... def __getitem__(self, index): ... if index < 0: ... raise indexerror("negative integers forbidden") ... return list.__getitem__(self, index) ... >>> seq = strictlist([1,2,3]) >>> seq[-1] traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 4, in __getitem__ indexerror: 'negative integers forbidden'
Comments
Post a Comment