Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Created February 1, 2019 17:41
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 saintsGrad15/474639b9e7b0f929f4cafb430e2a8ecb to your computer and use it in GitHub Desktop.
Save saintsGrad15/474639b9e7b0f929f4cafb430e2a8ecb to your computer and use it in GitHub Desktop.
A simple list implementation that yields None or a defined default if an out-of-bounds index is referenced.
class DefaultList(list):
def __init__(self, iterable=[], default=None):
super(self.__class__, self).__init__(iterable)
self.default = default
def __getitem__(self, index):
"""
If 'index' is outside of the bounds (including negative indexing) of the list,
return 'self.default.'
:param: index (int): The numerical index to return.
:return: (any) The element at index 'index.'
If that index doesn't exist, 'self.default.'
"""
length = len(self)
if index in range(-1 * length, length):
return super(self.__class__, self).__getitem__(index)
else:
return self.default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment