Skip to content

Instantly share code, notes, and snippets.

@zsrinivas
Last active November 20, 2015 18:38
Show Gist options
  • Save zsrinivas/c0c2ee1e7c6535ef8c3d to your computer and use it in GitHub Desktop.
Save zsrinivas/c0c2ee1e7c6535ef8c3d to your computer and use it in GitHub Desktop.
class defaultlist(object):
def __init__(self, factory, data=None):
self.factory = factory
self.list = []
self.data = data
def __getitem__(self, x):
if x >= len(self.list):
self.list.extend([self.factory() for _ in range(len(self.list), x + 1)])
return self.list[x]
def __repr__(self):
return str(self)
def __str__(self):
if len(self.list) == 0:
return '(' + str(self.data) + ')[...]'
return ''.join(['(', str(self.data), ')[', ', '.join(map(str, self.list)), ', ...]'])
def __setitem__(self, x, v):
if x >= len(self.list):
self.list.extend([self.factory() for _ in range(len(self.list), x + 1)])
self.list[x] = v
def main():
factory = lambda: defaultlist(factory)
list_of_lists = defaultlist(factory)
print (list_of_lists[0])
list_of_lists[0][3].data = 20
print (list_of_lists[0])
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment