Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list set value at index if index does not exist

Is there a way, lib, or something in python that I can set value in list at an index that does not exist? Something like runtime index creation at list:

l = []
l[3] = 'foo'
# [None, None, None, 'foo']

And more further, with multi dimensional lists:

l = []
l[0][2] = 'bar'
# [[None, None, 'bar']]

Or with an existing one:

l = [['xx']]
l[0][1] = 'yy'
# [['xx', 'yy']]
like image 755
user1538560 Avatar asked Mar 13 '14 19:03

user1538560


1 Answers

There isn't a built-in, but it's easy enough to implement:

class FillList(list):
    def __setitem__(self, index, value):
        try:
            super().__setitem__(index, value)
        except IndexError:
            for _ in range(index-len(self)+1):
                self.append(None)
            super().__setitem__(index, value)

Or, if you need to change existing vanilla lists:

def set_list(l, i, v):
      try:
          l[i] = v
      except IndexError:
          for _ in range(i-len(l)+1):
              l.append(None)
          l[i] = v
like image 109
jonrsharpe Avatar answered Oct 10 '22 19:10

jonrsharpe