0

I only want to append [1] to the first list element of the main list, tree, but [1] gets appended to each list element.

tree = [[]] * 5
tree[0].append([1])
print tree

>>>[[[1], [1], [1], [1], [1]]]

What I want:

>>>[[[1]],[],[],[],[]]
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
tanzola
  • 79
  • 1
  • 7
  • 1
    see [the several questions linked to here](http://stackoverflow.com/questions/19249201/how-to-create-a-number-of-empty-nested-lists-in-python#comment28494052_19249201) and the question on that page. – Tadhg McDonald-Jensen Apr 01 '16 at 01:11

3 Answers3

0

The way you create the list (tree = [[]] * 5) is the problem. All the 5 lists inside the list are identical objects which you can see when using the method id():

>>> tree = [[]] * 5
>>> id(tree[0])
139859652123032
>>> id(tree[1])
139859652123032

The solution would be:

>>> tree = [[], [], [], [], []]
>>> tree[0].append([1])
>>> tree
[[[1]], [], [], [], []]
dron22
  • 1,235
  • 10
  • 20
0

My problem was that multiplying with * creates references of the same element. I should use:

tree = [[] for i in xrange(5)]
tanzola
  • 79
  • 1
  • 7
0

Use a for statement to iterate and add each branch

tree = [[] for i in xrange(5)]   
    # xrange() and range() will have the same result, but the former is a cheaper iterator

Finally, append '[1]' to the first list

tree[0].append([1])
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Python Cheese
  • 157
  • 1
  • 10