2

I've found a good way of looped list making here. And the code run just as I needed.

x=["alpha","betta", "gamma"]
y=[[] for _ in range(len(x))]
y[1]=3

Will give me [[], 3, []] as expected. But when I tried to upscale the code:

z=[10,20,30]
x=["alpha","betta"]
y=[[] for _ in range(len(z))]
y=[y for _ in range(len(x))]
y[1][1]=4

Will give me the correct shape but I will get [[[], 4, []], [[], 4, []]]

Instead of [[[], [], []], [[], 4, []]] I've obviously fallen into the trap mentioned in the link but I don't understand why and how to avoid this problem

Zoe
  • 27,060
  • 21
  • 118
  • 148
TRV
  • 53
  • 1
  • 1
  • 9
  • It's spelled "beta" ;) – JMAA Oct 20 '18 at 10:40
  • now I'm not sure it's really a duplicate, as OP did the first 2D thing creation properly. The mistake is just passing the same reference over and over again. reopening as OP didn't understand why even by doing some research – Jean-François Fabre Oct 20 '18 at 10:41
  • Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – pault Oct 20 '18 at 10:45

2 Answers2

3

This is where your code goes wrong:

y=[y for _ in range(len(x))]

Because you are essentially creating two pointers to the same list (i.e. y). Instead you could try something like this:

y=[y.copy() for _ in range(len(x))]

Which solves your problem since you create new lists.

MaartenGr
  • 191
  • 4
1

this solution fixes the issue you're demonstrating but what if you do this instead:

y=[[] for _ in range(len(z))]
y=[y.copy() for _ in range(len(x))]
y[1][1].append(12)

here I'm using a list reference instead of overwriting it so I get:

[[[], [12], []], [[], [12], []]]

Damn. Why this? because copy creates a shallow copy, you need to deepcopy

import copy
y=[copy.deepcopy(y) for _ in range(len(x))]
y[1][1].append(12)

prints:

[[[], [], []], [[], [12], []]]

now choose the one that suits your needs best.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219