1

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

A1122
  • 1,324
  • 3
  • 15
  • 35

2 Answers2

3

You could use Python's arithmetic operators to generate your nested lists (this method is more performant than iterating with nested for loops):

def listmaker(n, m):
    # n = number of lists in the 3rd layer 
    # m = number of lists in the 2nd layer
    return [[[]] * n] * m 

listmaker(2, 2)
# [[[],[]],[[],[]]]

# you could use the "+" operator to create unequal numbers of lists in the 3rd layer
listmaker(2, 2) + listmaker(1, 1)
# [[[], []], [[], []], [[]]]
Daniel
  • 2,345
  • 4
  • 19
  • 36
  • This certainly is a very wrong way to do it(at least in Python 2.7). If I do `l = [ [ [] ] * 2] * 2`, and then `l[0][0].append(1)`, then `l` becomes `[[[1], [1]], [[1], [1]]]`, which should clearly not happen. – Rahul Jul 01 '16 at 08:20
  • Actually, the behavior you describe is correct in Python. Using operators like `*` in this context creates references to the `[]` objects, which means that when you change one such object (like you did with your `append()`), you change all of the references to that object. There are lots of SO questions that deal with this concept, for example: http://stackoverflow.com/questions/240178/. My answer is still more performant than a nested `for` loop for what the OP appears to want to do, without going down a long rabbit hole re.: the OP's possible intentions. – Daniel Jul 01 '16 at 18:25
  • Additionally, there are many other possible answers (using `map`, Numpy, etc.). It all depends on what the OP wants to do. – Daniel Jul 01 '16 at 18:32
0

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 range(j) ] for j in length ]
>>> res
[[[]], [[], []], [[], [], []], [[], [], [], []]]
Rahul
  • 502
  • 7
  • 16
  • you do not need to use loops, use normal "*" operator, `xrange` should be avoid as is is depreciated in python3 – Jerzyk Jul 01 '16 at 06:44
  • `*` operator should be avoided. see my comment on Daniel's answer. `xrange` converted to `range`. thanks. – Rahul Jul 01 '16 at 08:21