Python list value specified in index if index does not exist

Is there a way, lib or something in python, that I can set the value in the list at an index that does not exist? Something like creating a run-time index on a list:

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

And what's more, 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']] 
+7
python multidimensional-array
source share
3 answers

There is no built-in, but simple 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 modify 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 
+5
source share

You cannot create a list with spaces. You can use dict or this quick little guy:

 def set_list(i,v): l = [] x = 0 while x < i: l.append(None) x += 1 l.append(v) return l print set_list(3, 'foo') >>> [None, None, None, 'foo'] 
0
source share

If you really need the syntax in your question, defaultdict is probably the best way to get it:

 from collections import defaultdict def rec_dd(): return defaultdict(rec_dd) l = rec_dd() l[3] = 'foo' print l {3: 'foo'} l = rec_dd() l[0][2] = 'xx' l[1][0] = 'yy' print l <long output because of defaultdict, but essentially) {0: {2: 'xx'}, 1: {0: 'yy'}} 

This is not exactly a β€œlist of lists,” but it works more or less like.

You really need to specify a precedent, though ... the above has some advantages (you can access the indices without checking if they exist first), and some disadvantages - for example, l[2] in the usual dict will return KeyError , but in defaultdict it just creates an empty defaultdict , adds it and returns it.

Other possible implementations to support various syntactic sugars may include custom classes, etc., and will have other tradeoffs.

0
source share

All Articles