0

So I have divided my issue into 2 parts, both parts should be able to fixed with the same solution. Part 1 is the issue I have initially come across during testing of my code. Where I am trying to assign elements from one 2d array to another but instead it only assigns the last elements to the array instead. And part 2 is an issue that I will be facing later on but is still related.

---PART 1---

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[None]*4]*4

yval=0
for y in a:
    xval = 0
    for x in y:
        b[yval][xval] = x
        xval+=1
    yval+=1
print("Grid A:")
print(a)

print("Grid B:")
print(b)

My Output

Grid A:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Grid B:
[[7, 8, 9, None], [7, 8, 9, None], [7, 8, 9, None], [7, 8, 9, None]]

My Goal

Grid A:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Grid B:
[[1, 2, 3, None], [4, 5, 6, None], [7, 8, 9, None], [None, None, None, None]]

I don't really understand what is causing each subarray in b to be assigned the same elements. including the last one even though the initial for loop only iterates 3 times. Now there may be a simpler way to do this in python but I also need to be able to move one table over to another table but in a different location as well.

--- PART 2 ---

For example lets say I have a 2x2 array
[[a,b],
[c,d]]

And I want to place it in the bottom right corner of 4x4 array
[[ , , , ],
[ , , , ],
[ , , , ],
[ , , , ]]

My code is

a = [[1,2],[3,4]]
b = [[None]*4]*4

yval=0
for y in a:
    xval = 0
    for x in y:
        b[yval+2][xval + 2] = x
        xval+=1
    yval+=1
print("Grid A:")
print(a)

print("Grid B:")
print(b)

My goal would be
[[ , , , ],
[ , , , ],
[ , ,a,b],
[ , ,c,d]]

However my actual result is
[[ , ,c,d],
[ , ,c,d],
[ , ,c,d],
[ , ,c,d]]

1 Answer 1

1

Problem origin

The problem comes form the definition of b which as defined is a list of 4 times the same sub-list as the following code shows

b = [[None]*4]*4
b[0][0] = 1
print(b)

outputs

[[1, None, None, None],
 [1, None, None, None],
 [1, None, None, None],
 [1, None, None, None]]

Solution

b = [[None]*4 for _ in range(4)]
Sign up to request clarification or add additional context in comments.

2 Comments

Ah okay that does make sense. It didn't occur to me that the problem was that each sublist was coming from the same address.
@JaedonLippert : you are not the first one to get caught.

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.