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

3
  • It's spelled "beta" ;) Commented Oct 20, 2018 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 Commented Oct 20, 2018 at 10:41
  • Possible duplicate of List of lists changes reflected across sublists unexpectedly Commented Oct 20, 2018 at 10:45

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.