Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultdict equivalent for lists [duplicate]

Is there\How would you build an equivalent of python's very useful collections.defaultdict?

Imagined usage of such a container:

>>> a = collections.defaultlist(0)
>>> a[2]=7
>>> a[4]='x'
>>> a
[0,0,7,0,'x']

UPDATE: I've added a follow up question to add even more functionality to this construct

like image 216
Jonathan Livni Avatar asked Jan 03 '12 22:01

Jonathan Livni


1 Answers

A slightly enhanced version from answer by @Finn.

class defaultlist(list):
    """List returning default value when accessing uninitialized index.

    Original implementation: http://stackoverflow.com/a/8719940/315168
    """

    def __init__(self, fx):
        self._fx = fx

    def __setitem__(self, index, value):
        while len(self) <= index:
            self.append(self._fx())
        list.__setitem__(self, index, value)

    def __getitem__(self, index):
        """Allows self.dlist[0] style access before value is initialized."""
        while len(self) <= index:
            self.append(self._fx())
        return list.__getitem__(self, index)
like image 143
Mikko Ohtamaa Avatar answered Oct 10 '22 02:10

Mikko Ohtamaa