0

Let a be a 2-dimentional list with each element being a set. For example, let a be a (3,3) list, I initialize as follows

a = [set()] * 3
a = [a] * 3

I now want to assign a[1][1] with another set. I do

a[1][1] = set([1,2,3])

But in doing this, not only a[1][1], but also a[0][1] and a[2][1] are assigned to this new set. It's so weird to me. How does this happen? How should I correct it?

Thanks!!


I set a to be a 2D list array because I want a to work like a = cell(3,3) as in Matlab.

zxzx179
  • 187
  • 7

1 Answers1

1

You have an aliasing problem. You are sharing a list object when you do

a = [a] * 3

Every index of a then references the same list. You have 3 list objects which all reference the same object.

You can see that this is unrelated to the set structure by doing:

a = [set()] * 3
a = [a] * 3
print(a)
a[1][1] = "Test"
print(a)

output:

[[set(), set(), set()], [set(), set(), set()], [set(), set(), set()]]
[[set(), 'Test', set()], [set(), 'Test', set()], [set(), 'Test', set()]]

You should so something like:

a = [[set() for _ in range(3)] for _ in range(3)]

print(a)

a[1][1] = {1, 2, 3}

print(a)

To ensure you have distinct lists so you wont have this issue.

You can also do:

a = [[set()] * 3 for _ in range(3)]
print(a)
a[1][1] = {1, 2, 3}
print(a)

Both Produce the same Output:

[[set(), set(), set()], [set(), set(), set()], [set(), set(), set()]]
[[set(), set(), set()], [set(), {1, 2, 3}, set()], [set(), set(), set()]]
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57