On Fri, Nov 20, 2015 at 6:39 PM, Chris Angelico <ros...@gmail.com> wrote: > My crystal ball suggests that defaultdict(list) might be useful here. > > ChrisA
I used something similar to this for some problem in hackerrank, anyway i think this is what you want. 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), ')['] + 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][10].data = 20 print (list_of_lists[0]) main() Gist: https://gist.github.com/c0c2ee1e7c6535ef8c3d -- https://mail.python.org/mailman/listinfo/python-list