Skip to content Skip to sidebar Skip to footer

Python List - "reserving" Space ( ~ Resizing)

I am given a list l and I want to do assignment: l[index] = val But there might be a case when the list is too small. So, I want to ensure I have space for the new value. Sometime

Solution 1:

If you're sure that a list -- and not, say, a dict -- is the best data structure for your use case, I propose the following class:

classrlist(list):
  def__init__(self, default):
    self._default = default
  def__setitem__(self, key, value):
    if key >= len(self):
      self += [self._default] * (key - len(self) + 1)
    super(rlist, self).__setitem__(key, value)

l = rlist(0)
print(l)
l[10] = 20print(l)
l[5] = 14print(l)

This class checks whether the index being assigned to is beyond the current length of the list, and automatically expands the list as required.

The code is compatible with both Python 2 and 3 (tested with 2.6.5 and 3.1.2).

This class could be handy if the structure is dense and you need to find the element by index as quickly as possible. If the structure is sparse, you should probably consider using a dictionary.

Solution 2:

Perhaps this does what you want:

defresize(l, newsize, filling=None):                                                                                  
    if newsize > len(l):                                                                                 
        l.extend([filling for x in xrange(len(l), newsize)])                                                 
    else:                                                                                                
        del l[newsize:]                  

Solution 3:

I came up with something that uses itertool.repeat().

import itertools

defassign(lst, idx, value, fill=None):
    diff = len(lst) - idx
    if diff >= 0:
        lst[idx] = value
    else:
        lst.extend(itertools.repeat(fill, -diff))
        lst.append(value)

That have the following behaviour:

>>> l = [0, 1, 2, 3, 4]
>>> assign(l, 2, 'new')
>>> l
[0, 1, 'new', 3, 4]
>>> assign(l, 8, 'new')
>>> l
[0, 1, 'new', 3, 4, None, None, None, 'new']
>>> assign(l, 10, 'new', fill=[])
>>> l
[0, 1, 'new', 3, 4, None, None, None, 'new', [], 'new']

Does this work for you?

Edit: Since the question was updated I've updated the answer.

Solution 4:

Try this:

defResizeList(some_list, length, null_item = None): 
    return some_list + [null_item 
                        for item inrange(length - len(lst))]

Post a Comment for "Python List - "reserving" Space ( ~ Resizing)"