class mylist(): def __init__(self,l): self.l = l def extend(self,index): diff = index + 1 - len(self.l) if diff > 0: self.l.extend([ None for x in range(diff) ] ) def __getitem__(self,index): # self.extend(index) ## depending on your taste return self.l[index] def __setitem__(self,index,value): self.extend(index) self.l[index] = value def __repr__(self): return self.l.__repr__() a = mylist([0,1,2,3]) print 'List: %s' % a # print a[5] ### this will throw an 'list index out of range' unless ### you comment out the bit in __getitem__ a[5] = 5 print 'List: %s' % a print a[5]
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question