I\'m trying to create a list equivalent for the very useful collections.defaultdict. The following design works nicely:
class defaultlist(list):
def __in
There is a python package available:
$ pip install defaultlist
Added indicies are filled with None by default.
>>> from defaultlist import defaultlist
>>> l = defaultlist()
>>> l
[]
>>> l[2] = "C"
>>> l
[None, None, 'C']
>>> l[4]
>>> l
[None, None, 'C', None, None]
Slices and negative indicies are supported likewise
>>> l[1:4]
[None, 'C', None]
>>> l[-3]
'C'
Simple factory functions can be created via lambda.
>>> l = defaultlist(lambda: 'empty')
>>> l[2] = "C"
>>> l[4]
'empty'
>>> l
['empty', 'empty', 'C', 'empty', 'empty']
It is also possible to implement advanced factory functions:
>>> def inc():
... inc.counter += 1
... return inc.counter
>>> inc.counter = -1
>>> l = defaultlist(inc)
>>> l[2] = "C"
>>> l
[0, 1, 'C']
>>> l[4]
4
>>> l
[0, 1, 'C', 3, 4]
See the Documentation for any further details.