I would like to create a python multi-dimensional empty list without very long codes. So I tried this:
a = [[[]] * 2] * 2
It turns out that when I print(a), I got the multi-dimensional empty list:
[[[], []], [[], []]]
But when I append something into one of the empty list:
a[0][0].append(np.array((1.5,2.5)))
All the empty lists got this np.array:
[[[array([1.5, 2.5])], [array([1.5, 2.5])]], [[array([1.5, 2.5])], [array([1.5, 2.5])]]]
But if I create the multi-dimensional empty list like below:
b = []
for i in range(2):
c = []
for j in range(2):
c.append(([]))
b.append(c)
It works. When I print(b), I still got:
[[[], []], [[], []]]
But when I do
b[0][0].append(np.array((1.6,2.6)))
then print(b), I got:
[[[array([1.6, 2.6])], []], [[], []]]
which is what I want.
Why is does happen?
I am using Python 3.6.8
This is my codes:
This is wrong:
a = [[[]] * 2] * 2
print(a)
a[0][0].append(np.array((1.5,2.5)))
print(a)
This is what I want:
b = []
for i in range(2):
c = []
for j in range(2):
c.append(([]))
b.append(c)
print(b)
b[0][0].append(np.array((1.6,2.6)))
print(b)
Why a = [[[]] * 2] * 2
cannot work, and how can I create this shortly? Thanks!