0
def matrix():
    rows = 10
    columns = 9

    arr = [[0]*columns]*rows
    file = open("blAblA")
    for i in range(rows):
        for j in range(columns-1):
            arr[i][j] = int(file.readline().rstrip("\n"))
        print(arr[i])
    print("-------------------------------------------------")

    for k in range(rows):
        print(arr[k])

matrix()

why are these 2 "for" loop gives me different output like this: Image

Archie
  • 15
  • 7
  • I suspect the code you've shown us isn't the code that generated that output. The output of the second loop in that image is the final row over and over, implying you actually printed `arr[i]` while looping with `k` – Kemp Mar 27 '21 at 15:58
  • The problem is that you're performing a shallow copy when you originally create `arr`. Try `arr = [[0 for _ in range(columns)] for _ in range(rows)]` – jdowner Mar 27 '21 at 16:01
  • No u got this something wrong ı guess. My purpose is reading data from text and add into array which is arr. I do that on first 2 for and ı just wanted to see like a chart thats why I wrote print end of the second for. Then ı want to add some values on the last column which is 8. But ı couldnt cuz ı cant reach to the correct values. These 2 prints gives different outputs. If u want u can try – Archie Mar 27 '21 at 16:05
  • for jdowner: https://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/ isn't it the same thing ? – Archie Mar 27 '21 at 16:07
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – wjandrea Mar 27 '21 at 17:31
  • @Kemp The code is correct. You could test it for yourself by removing the file stuff and filling the array with, say, `arr[i][j] = random.randrange(10)`. The problem is that all the rows are copies of the same list. – wjandrea Mar 27 '21 at 17:38
  • In the future, please provide a [mre] including input, plus output as text, [not a picture](https://meta.stackoverflow.com/q/285551/4518341) – wjandrea Mar 27 '21 at 17:39
  • @wjandrea Ah yes, I missed the creation of the lists. Good spot. – Kemp Mar 27 '21 at 17:50

0 Answers0