Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class instance not iterable

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
like image 754
matttm Avatar asked Jun 26 '26 06:06

matttm


2 Answers

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))
like image 190
mhawke Avatar answered Jun 27 '26 21:06

mhawke


When you do the following for a list -

pointList += newPoint

It is similar to calling pointList.extend(newPoint) , and in this case newPoint needs to be an iterable, whose elements will get added to pointList.

If what you want is to simply add the element into the list, you should use list.append() method -

pointList.append(newPoint)
like image 36
Anand S Kumar Avatar answered Jun 27 '26 21:06

Anand S Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!