0

I am working on a little project that involves working with and transforming coordinates and my code behaves in a way that I can't explain. Example code:

koord = [[60,10],[70,18],[61,21],[69,11]]
min_X = [255,255]

for i in range(len(koord)):
    if koord[i][0]<min_X[0]:
        min_X=koord[i]
print(min_X)

for i in range(len(koord)):
    for j in range(2):
        koord[i][j]=koord[i][j] - min_X[j]
    print(min_X)

I expect it to always print [60, 10], but instead I get

[60, 10]
[0, 0]
[0, 0]
[0, 0]
[0, 0]

Why does the min_X value change? It seams to redo the first for-loop but why? Can someone explain why this happens and how I can fix it?

mac13k
  • 2,423
  • 23
  • 34
miasann
  • 13
  • 2

1 Answers1

1

The first for loop assigns min_X to point to the first coordinate pair list, so now min_X === koord[0]. Then the second for loop updates koord[0], so min_X sees the same update since it is the same (list) object.

Here's a more contained example:

a = [ 10 ]
b = a
a[0] -= b[0]
print(b)
# this returns [0]
J. Gómez
  • 96
  • 4
  • Ok. But ist there a way to get it to not "link" them together, but keep them as seperate variables? – miasann Aug 31 '20 at 17:03
  • You can make a copy of the list, e.g., `newList = list(oldList)`. See this: https://stackoverflow.com/a/2612815/2366407 . – J. Gómez Aug 31 '20 at 17:19