fightstarr20
fightstarr20

Reputation: 12628

Python unsupported operand type on a list

I have the following 2d python list mylist of coordinates...

[[294.0, 351.0], [486.0, 255.5]]

I am trying to determine which one of these points is closest to the center of a 500x500 area like this...

def sqr_dist(a, b):
    # return square of distance between points a and b #
    return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2

central = min( mylist, key=lambda r: sqr_dist( (mylist[0], mylist[1]), (500, 500) ) )

But I am getting error...

TypeError: unsupported operand type(s) for -: 'list' and 'int'

I assume this is telling me that I can't use min on a list

If this is the case then what is my alternative?

Upvotes: 1

Views: 182

Answers (3)

AnkushRasgon
AnkushRasgon

Reputation: 820

sqr_dist( (mylist[0], mylist[1]), (500, 500) )
b=(500, 500)
a[0]=[294.0, 351.0]
b[0]=500

so you cannot subtract list with integer(a[0] - b[0]) as your error shows - symbol -: 'list' and 'int'

the correct way to do it

central = min( mylist, key=lambda r: sqr_dist( r, (500, 500) ) )

Upvotes: 1

Akaisteph7
Akaisteph7

Reputation: 6554

You were just using lambda wrong.

Your error means that you are trying to do a -, subtraction, between a list, and an int. That is because you were passing both to your sqr_dist function. The correct way to do this is:

central = min( mylist, key=lambda r: sqr_dist( r, (500, 500) ) )

Upvotes: 1

Kevin Winata
Kevin Winata

Reputation: 454

The problem is because of the a[0]-b[0]. a[0] is a list, b[0] is an integer. So what you should do is:

mylist = [[294.0, 351.0], [486.0, 255.5]]

def sqr_dist(a, b):
    # return square of distance between points a and b #
    return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2

central = min(mylist, key=lambda r: sqr_dist( r, (500.0, 500.0) ) )

The difference is that now I'm passing the r (a list) to the sqr_dist in the lambda. The problem is with the lambda function.

Upvotes: 1

Related Questions