0

Code:

A = [[2,3],[3,4], [5,2]]
B = [[1,2],[3,2]]
result=[];
for i in range(len(A)):
    #AA=[];
    for j in range(len(B)):
        AA.append(0)
        print("AA=",(AA,i,j))
result.append(AA)
print(f"result at {i}",result)

The output for this code:

AA= ([0], 0, 0)
AA= ([0, 0], 0, 1)
result at 0 [[0, 0]]
AA= ([0, 0, 0], 1, 0)
AA= ([0, 0, 0, 0], 1, 1)
result at 1 [[0, 0, 0, 0], [0, 0, 0, 0]]
AA= ([0, 0, 0, 0, 0], 2, 0)
AA= ([0, 0, 0, 0, 0, 0], 2, 1)
result at 2 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

Why has the code not given me [[0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] output result at 2, as the final result for my code when I comment #AA=[] this empty list from the code. Can anyone explain to me clearly the concept of appending lists in this code?

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
  • You appended the same `AA` list to the `result` for every loop when you commented out the line that creates a new list to assign to `AA`. – metatoaster Jun 25 '21 at 03:39

0 Answers0