Building a list inside a list in python

You could append empty lists until you have enough to access the index you have data for:

while len(outerlist) <= idx:
    outerlist.append([])

However, you may want to use a dictionary instead, letting you implement a sparse object instead. A collections.defaultdict() object is especially useful here:

from collections import defaultdict

data = defaultdict(list)

data[2].append(3)
data[5].append(42)

data now has keys 2 and 5, each a list with one element. No entries for 0, 1, 3, or 4 exist yet.

Leave a Comment