1

Basically what I'm trying to do is, create a nestled list and set a value of one of its element as a function of other elements in the list.

>>> a = [[1]*5]*5
>>> a
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
>>> a[2][2] = a[0][2] + a[2][1]
>>> a
[[1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1]]
>>> a[3][2]   
2
>>> a[4][2]
2
>>> a[4][4]
1

I just set the value of a[2][2] but the same value got set to every element in the 3rd column. What is going on exactly and how can I get the desired behavior?

2 Answers 2

2

What happens is that a ends up containing five references to the same sublist. When you change one sublist, they all change.

To see this, apply id() to each of the sublists:

>>> map(id, a)
[8189352, 8189352, 8189352, 8189352, 8189352]

As you can see, they all have the same ID, meaning they are the same object.

To fix, replace

a = [[1]*5]*5

with

a = [[1]*5 for _ in range(5)]

Now the sublists are independent objects:

>>> map(id, a)
[21086256, 18525680, 18524720, 19331112, 18431472]
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is your list a contains five references to the same list. You need to do something like this:

a = []
for _ in range(5):
    a += [[1] * 5]

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.