0

I am creating a list with several sub-lists and sub-sub-lists like so:

a = [0.1, 0.2, 0.4, 0.8, 1.2]
b = [[]] * 3
c = [[]] * 4
# Final list.
d = [[b, c]] * len(a)

I need to create it this way because it depends on the length of various other lists, this is just a simplified example.

When I try to append a single element to d:

d[0][0][0].append(a[2])

I get the same element repeated throughout the list:

[[[[0.4], [0.4], [0.4]], [[], [], [], []]], [[[0.4], [0.4], [0.4]], [[], [], [], []]], [[[0.4], [0.4], [0.4]], [[], [], [], []]], [[[0.4], [0.4], [0.4]], [[], [], [], []]], [[[0.4], [0.4], [0.4]], [[], [], [], []]]]

I understand this is a problem with how I'm creating d but I'm not sure how can I prevent this behaviour.

Gabriel
  • 40,504
  • 73
  • 230
  • 404

0 Answers0