Issue 41827: 2D array issue - Python tracker

This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: eric.smith, jeetshahj12375, serhiy.storchaka
Priority: normal Keywords:

Created on 2020-09-21 18:49 by jeetshahj12375, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
matrix summation-Copy1.ipynb jeetshahj12375, 2020-09-21 18:49
Messages (6)
msg377268 - (view) Author: jeet shah (jeetshahj12375) Date: 2020-09-21 18:49
See difference in output by changing array definition.
msg377270 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-09-21 19:06
Please provide the output you see and the output you expect.

And it would be better if you could just post the code into the comment window. I, for one, cannot run your .ipynb file.
msg377283 - (view) Author: jeet shah (jeetshahj12375) Date: 2020-09-21 21:03
after = [[1,2],[3,4]]
rows, cols = (len(after), len(after[0])) 

before = [[0]*cols]*rows

# before = [[0 for i in range(cols)] for j in range(rows)]  #uncomment this array definition and comment above one... see difference in output.

print(before)

def calculation(a,b):
    s = after[0][0]
    for x in range(a+1):
        for y in range(b+1):
                s += before[x][y]
    before[a][b] = after[a][b] - s
    
def cal2():
    for x in range(len(after)):
        for y in range(len(after[0])):
            calculation(x,y)
    before[0][0] = after[0][0]
    print(before)
cal2()


#expected output: [[1, 1], [2, 0]]
msg377286 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-09-21 21:39
Your example is too complex to work through in my head, but I suspect this is the issue you're seeing: https://docs.python.org/3/faq/programming.html#why-did-changing-list-y-also-change-list-x

In any event, this is almost certainly not a bug in Python, but rather in your code. You might want to ask this question on the python-list mailing list https://mail.python.org/mailman/listinfo/python-list or on Stack Overflow, which are more appropriate venues than the bug tracker.
msg377343 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2020-09-22 18:26
See https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list.
msg377346 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-09-22 19:22
Thanks, Serhiy. That's a better section than I found.

I'm going to close this. @jeetshahj12375: If you can show that this is a bug in python, please re-open this issue.