Skip to content

Instantly share code, notes, and snippets.

@maxnordlund
Created March 14, 2017 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxnordlund/7a8ed9626f2109d4bf688604a6ac324b to your computer and use it in GitHub Desktop.
Save maxnordlund/7a8ed9626f2109d4bf688604a6ac324b to your computer and use it in GitHub Desktop.
Default list in python, á la defaultdict.
class DefaultList(list):
"""
List that always returns a value
If you try to access an missing index, it will fill up this list with
empty lists for all missing indices before returning the requested
index. This will be the last element since lists are ordered.
A consequence of this is that `for` loops over this list will never
stop.
"""
def __getitem__(self, index):
try:
# This also handles slice objects, which always will return a
# new list, and can thus never fail
return super().__getitem__(index)
except IndexError:
# Fill the list with empty ones upto the requested index
self[len(self):index + 1] = ([] for _ in range(len(self), index + 1))
return super().__getitem__(index)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment