Home > Enterprise >  "list indices must be integers or slices, not [custom class]" but I'm specifying an i
"list indices must be integers or slices, not [custom class]" but I'm specifying an i

Time:04-23

I have a custom class defined like so:

class points:
    def __init__(self, x=0, h=0, l=0):
        self.x = x
        self.h = h
        self.l = l #bool location, 0 for start point, 1 for endpoint

Further in my code, I successfully build a list of these points, and the error comes when I attempt the following conditional:

for i in points_list:
    if (sorted_points[i].l == 0):

Python thinks that sorted_points[i].l isn't an integer or slice (it thinks it's a points object), but the only thing it can be is an integer (I even try printing out the list of sorted_points l values, and they are all 1 or 0), so I am very confused.

CodePudding user response:

for el in my_list syntax iterates over the elements of my_list. Look:

class A:
    pass

l = [A(), A(), A()]
for el in l:
    print(type(el)) # <class '__main__.A'>

So in your case you should use your i as instance of point.

for i in points_list:
    if i.l == 0: # if it's boolean, you should even write if not i.l
        ...

If you want to iterate over indexes, use range

for i in range(len(points_list)):
    if not sorted_points[i].l:
        ...
  • Related