# [Tutor] min() & mutable sequences

dman dsh8290@rit.edu
Fri, 21 Dec 2001 13:05:04 -0500

```On Thu, Dec 20, 2001 at 01:43:27PM +0800, Andy W wrote:
| Hi people,
|
| First to give some background: I have a list of instances, each has an
| attributes "distance". I want to get the instance with the smallest
| distance.
|
| I have at present:-
|
| robots=[...] #The ... is a whole lot of instances :)
| closest=min([robot.distance for robot in robots])
|
| Okay, I now have the closest *distance*.
| Say more than one instance has the same distance, will min() return the
| first instance with that smallest distance? Because if that is so, I could
| then just get the related instance using:-

No.  min() returns the smallest object in the list.  In this case the
object is a number, not a robot.

| closest_index=[robot.distance for robot in robots].index(closest)
| #Yeah, I used that list comprehension twice, this is just for demonstration,
| though.
| closest_robot=robots[closest_index]

This could be done, but I think it is inefficient.  How about defining
__lt__ in your class?  Then you don't need to create separate lists
using the distances.

| Is there a better way to do it?
|
| I guess I could iterate over the list, and keep a smallest distance variable
| somewhere. I guess I've become somewhat of a list-comprehension-addict
| *grin*

This should do it :

m = robots[0]
d = m.distance
for r in robots[1:] :
if r.distance < d : m = r
print m

certainly there are other ways, though.

I'm kinda surprised that min() doesn't take a comparison function like
sort does.  Say, I just thought of :

robots.sort( lamda a , b : a.distance < b.distance )
print robots[0]

If you sort it, the minimum will be the first element in the list :-).

-D

--

If your company is not involved in something called "ISO 9000" you
probably have no idea what it is.  If your company _is_ involved in ISO
9000 then you definitely have no idea what it is.
(Scott Adams - The Dilbert principle)

```