0

The question is actually pretty simply, just look at the code:

In [1]: collection = [[]] * 4

In [2]: collection
Out[2]: [[], [], [], []]

In [3]: collection[0].append(1)

In [4]: collection
Out[4]: [[1], [1], [1], [1]]

Why append 1 to collection[0] also append it to all the other dimensions? If that's not the correct way to add element into a specific dimension, then what's the right way?

Amarth Gûl
  • 1,040
  • 2
  • 14
  • 33
  • >>> collection = [[] for i in range(4)] >>> collection [[], [], [], []] >>> collection[0].append(1) >>> collection [[1], [], [], []] – Fred May 25 '17 at 06:19
  • @Fred Awesome!! I began to understand, is it because all these dimensions I wrote share the same memory as i just duplicate them? – Amarth Gûl May 25 '17 at 06:27
  • @AmarthGûl you can try "id(collection[0])" "id(collection[1])".They point to the same element. – lsv May 25 '17 at 06:30
  • `In [1]: col = [[]] * 4 In [2]: id(col[0]) Out[2]: 1973526363976 In [3]: id(col[1]) Out[3]: 1973526363976` They did... thank you! – Amarth Gûl May 25 '17 at 06:32

0 Answers0