Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autogrowing list in Python?

Tags:

python

list

I need a list-like object that will "autogrow" whenever a slot number greater or equal to its length is accessed, filling up all the newly created slots with some pre-specified default value. E.g.:

# hypothetical DefaultList class
x = DefaultList(list('abc'), default='*')
x[6] = 'g'
print x[2], x[4], x[6], x[8]  # should print 'c * g *'

Thanks!

PS. I know it is not hard to implement a class like this, but I avoid wheel-reinvention as much as possible, especially if a particularly efficient/well-designed wheel already exists.

PS2. A dict (or a collections.defaultdict) is not an acceptable implementation of the desired data structure. For why, see here: http://groups.google.com/group/comp.lang.python/msg/bcf360dfe8e868d1?hl=en

like image 736
kjo Avatar asked Feb 28 '11 19:02

kjo


People also ask

Can you grow a list in Python?

There are four methods to add elements to a List in Python. append(): append the object to the end of the list. insert(): inserts the object before the given index. extend(): extends the list by appending elements from the iterable.

Can you reassign a list in Python?

List in python is mutable types which means it can be changed after assigning some value. The list is similar to arrays in other programming languages.

What does list [] mean in Python?

A list is an ordered and mutable Python container, being one of the most common data structures in Python. To create a list, the elements are placed inside square brackets ([]), separated by commas. As shown above, lists can contain elements of different types as well as duplicated elements.


2 Answers

class DefaultList(list):
    def __init__(self,*args,**kwargs):
        list.__init__(self,*args)
        self.default=kwargs.get('default',None)
    def __getitem__(self,key):
        # retrieving an item does not expand the list
        if isinstance(key,slice):
            return [self[elt] for elt in range(key.start,key.stop,key.step)]
        else:
            try:
                return list.__getitem__(self,key)
            except IndexError:
                return self.default
    def __setitem__(self,key,value):
        # setting an item may expand the list
        try:
            list.__setitem__(self,key,value)
        except IndexError:
            self.extend([self.default]*(key-len(self)))
            self.append(value)

x = DefaultList(list('abc'), default='*')
print(x)
# ['a', 'b', 'c']
x[6] = 'g'
print(x)
# ['a', 'b', 'c', '*', '*', '*', 'g']
print x[2], x[4], x[6], x[8]  # should print 'c * g *'
# c * g *
print(x[2:9:2])
# ['c', '*', 'g', '*']
like image 166
unutbu Avatar answered Oct 23 '22 11:10

unutbu


I would use a sparse data structure (1xn matrix).

like image 26
SiggyF Avatar answered Oct 23 '22 12:10

SiggyF