class instance not iterable

matttm picture matttm · Oct 8, 2015 · Viewed 10.9k times · Source

In my func, I have:

        """
        Iterates 300 times as attempts, each having an inner-loop
        to calculate the z of a neighboring point and returns the optimal                 
        """

        pointList = []
        max_p = None

        for attempts in range(300):

            neighborList = ( (x - d, y), (x + d, y), (x, y - d), (x, y + d) )

            for neighbor in neighborList:
                z = evaluate( neighbor[0], neighbor[1] )
                point = None
                point = Point3D( neighbor[0], neighbor[1], z)
                pointList += point
            max_p = maxPoint( pointList )
            x = max_p.x_val
            y = max_p.y_val
        return max_p

I'm not iterating over my class instance, point, but I nevertheless get:

    pointList += newPoint
TypeError: 'Point3D' object is not iterable

Answer

mhawke picture mhawke · Oct 8, 2015

The problem is this line:

pointList += point

pointList is a list and point is a Point3D instance. You can only add another iterable to an iterable.

You can fix it with this:

pointList += [point]

or

pointList.append(point)

In your case you do not need to assign None to point. Nor do you need to bind a variable to the new point. You can add it directly to the list like this:

pointList.append(Point3D( neighbor[0], neighbor[1], z))