min, max with position

Chris Angelico rosuav at gmail.com
Sat Jun 4 17:50:24 EDT 2022


On Sun, 5 Jun 2022 at 07:46, Michael F. Stemper
<michael.stemper at gmail.com> wrote:
>
> Python contains built-in functions that return the minimum or
> maximum items in a list.
>
>   >>> l = [1.618033,3.141593,2.718282]
>   >>> min(l)
>   1.618033
>   >>> max(l)
>   3.141593
>   >>>
>
> Are there similar functions that return not only the minimum
> or maximum value, but also its position?
>
>   >>> specialmin(l)
>   (0,1.618033)
>   >>> specialmax(l)
>   3.141593
>   >>>
>

No, but it shouldn't be too hard to make it if you want it. The
obvious option of calling max/min on the enumerated list won't work on
its own, since the index comes before the value, but with a key
function it would work fine:

>>> min(enumerate(l), key=lambda x: x[1])
(0, 1.618033)
>>> max(enumerate(l), key=lambda x: x[1])
(1, 3.141593)

ChrisA


More information about the Python-list mailing list