min, max with position

Chris Angelico rosuav at gmail.com
Sat Jun 4 18:02:18 EDT 2022


On Sun, 5 Jun 2022 at 08:00, dn <PythonList at danceswithmice.info> wrote:
>
> On 05/06/2022 06.56, Dennis Lee Bieber wrote:
> > On Sat, 4 Jun 2022 13:36:26 -0500, "Michael F. Stemper"
> > <michael.stemper at gmail.com> declaimed the following:
> >
> >>
> >> Are there similar functions that return not only the minimum
> >> or maximum value, but also its position?
> >>
> >       If it isn't in the library reference manual, NO...
> >
> >       But it also isn't that difficult to write...
> >
> >>>> def whatAt(function, data):
> > ...   what = function(data)
> > ...   at = data.index(what)
> > ...   return (at, what)
> > ...
> >>>> l = [      1.618033,       3.1415923536,   2.718282        ]
> >>>> whatAt(min, l)
> > (0, 1.618033)
> >>>> whatAt(max, l)
> > (1, 3.1415923536)
> >>>>
> >
> > (properly, I should either reverse the order of the return value, or change
> > the name to atWhat() )
>
> ...and remembering the special case:
> if the what value appears more than once in the list, the where?at will
> report the first/'left-most' index only.
>

Which is consistent with the vanilla min() function.

>>> min([1, 1.0])
1

ChrisA


More information about the Python-list mailing list