Search code examples
pythonlistprintingtry-except

Order of print statements affecting array values in Python 3.7


If I print pts[0][0] before the set of if statements, the statement print("final pts: ", pts) always prints an empty array. However, if I print pts[0][0] after the set of if statements, the line print("final pts: ", pts) displays the correct values.

I believe it has something to do with the pts.pop(0) line because that doesn't properly work either. It doesn't work properly when i = 2.

Can anyone reproduce this result? Why does the print statement affect list values?

from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import numpy as np

x = [10, 24, 23, 23, 3]
y = [12, 2, 3, 4, 2]

skpoints = list(zip(x, y))

for i in skpoints:
    print(i)

limits = np.arange(-1, 2)

pts = []
cutoff = 10
master = []

for i in range(len(skpoints)):
    pts = []
    temp = 1000
    print("\ni: ", i)
    for j in limits:
        try:
            dist = np.sqrt((skpoints[i][0] - skpoints[i + j][0]) ** 2 + (skpoints[i][1] - skpoints[i + j][1]) ** 2)
            print(dist)
            if 0 < dist < temp and (skpoints[i] and skpoints[i+j]) not in pts and dist < cutoff:
                print('pts before if statements', pts[0])

                # if its empty, add point right away
                if not master or not pts:
                    pts.append([dist, skpoints[i], skpoints[i + j]])
                # if dist is smaller than previous distance, replace distance and points
                elif dist < pts[0][0]:
                    pts.pop(0)
                    pts.append([dist, skpoints[i], skpoints[i + j]])
                elif dist == temp and (skpoints[i] and skpoints[i+j]) not in pts:
                    pts.append([skpoints[i], skpoints[i + j]])
                temp = dist
                print('pts after if statements', pts[0])
        except IndexError:
            j -= 1
    print("final pts: ", pts)



Solution

  • The problem is your blank try..catch; you're silently swallowing any and all exceptions without even printing any trace of them, which makes debugging a whole lot harder.

    The print('pts before if statements', pts[0]) statement is raising an IndexError exception if pts is empty, which bypasses the entire rest of the loop body and hence leads to an entirely different result.