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 =
If you really want 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
It isn't exactly a 'list of lists' but it works more or less like one.
You really need to specify the use case though... the above has some advantages (you can access indices without checking whether they exist first), and some disadvantages - for example, l[2]
in a normal dict will return a KeyError
, but in defaultdict
it just creates a blank defaultdict
, adds it, and then returns it.
Other possible implementations to support different syntactic sugars could involve custom classes etc, and will have other tradeoffs.