This is going to be very slow because self.nondept is a list and each node will not have to iterate the entire list -- O(n*m) time. Using a set wrapper on self.nondept before iterating will reduce the time complexity to O(n).