Python: How to avoid 'list assignment index out of range' -
tried search couldn't locate anything. i'm looking simplest replace
if mylist , len(mylist)>4
with shorter:
mylist = [1,2,3,4,5] if mylist , len(mylist)>4: print mylist[4], len(mylist)
since
if not mylist[4]
doesn't job.
you can try extending built-in type list
, override __getitem__()
intended behavior.
class mylist(list): def __getitem__(self, index): try: return super(mylist, self).__getitem__(index) except indexerror: return none mylist = mylist([1,2,3,4,5]) print mylist[4] #prints 5 print mylist[6] none #prints true
personally, i'd go adam smith's suggestion.
Comments
Post a Comment