0

The problem happens in the nested loop. In the first iteration everything is fine. The 2nd iteration over i, modifies the first list too and so on. Zeros across the 2d list should be diagonal

import math
def calcpyth(p1, p2):
    distance = math.sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))
    return distance

tuple0 = (42, 288)
tuple1 = (45, 326)
tuple2 = (50, 364)
tuple3 = (57, 400)

list = [tuple0, tuple1, tuple2, tuple3]
zeros = [[0]*len(list)]*len(list)
test = zeros

for i in range(len(test)):
    for j in range(len(test)):
        test[i][j] = calcpyth(list[i], list[j])

Arco Bast
  • 3,595
  • 2
  • 26
  • 53
Marius Kuzm
  • 159
  • 1
  • 9
  • general advise: try not to overwrite inbuild functions, like `list` ... a typical naming convention would be to call your own list `list_` – Arco Bast Feb 15 '20 at 17:34

1 Answers1

0

The problem is in the line

zeros = [[0]*len(list)]*len(list)

In that line of code, you create two lists:

  1. a list containing many 0s, with [0]*len(list)
  2. a list containing many references to the list created in step one. Here is the problem: You have created many references to one and the same list object. This explains the weird behaviour: If you change your nested list at one place, all 'sublists' appear to be changed as well.

So, what you would probably like to do, is to create a list containing many indepent lists that all contain 0s. Try:

zeros = [[0 for lv in range(len(list))] for lv in range(len(list))]
Arco Bast
  • 3,595
  • 2
  • 26
  • 53