A1122 A1122 - 5 months ago 19
Python Question

Creating empty 3-layer nested list

If I want to create a 3-layer nested list like

list = [[[],[]],[[],[]]]
, what's the appropriate way to do this? I saw someone else posted solution for the 2-layer nested list as
lst = [[] for _ in xrange(a)]
. Is there a more generalized way to create this nested list without establishing how many lists are in the third-layer?

Also, is there a way to create unequal number of lists in the third layer? For example:
list = [[[],[]],[]]
, where the
len(list[0])=2
and
len(list[1])=0

Answer

There is a way if you know the lengths of the third layer lists beforehand.

>>> length = [1,2,3,4] # indicates the lengths of the third layer lists
>>> res = [ [ [] for i in xrange(j) ] for j in length ]
>>> res
[[[]], [[], []], [[], [], []], [[], [], [], []]]
Comments