Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the maximum element of a slice of a list

Tags:

python

slice

max

I am trying to simplify this function at his maximum, how can I do?

def eleMax(items, start=0, end=None):
    if end is None:
        end = len(items)
    return max(items[start:end])

I thought of

def eleMax(items, start=0, end=-1):
    return max(items[start:end])

But the last element is deleted from the list.

like image 788
Natim Avatar asked Dec 06 '25 20:12

Natim


2 Answers

You can just remove these two lines:

if end is None:
    end = len(items)

The function will work exactly the same:

>>> a=[5,4,3,2,1]
>>> def eleMax(items, start=0, end=None):
...     return max(items[start:end])
...
>>> eleMax(a,2)   # a[2:] == [3,2,1]
3
like image 54
adamk Avatar answered Dec 08 '25 09:12

adamk


Just use max(items).

Python ranges are 'half-open'. When you slice a list in Python with [start:end] syntax, the start is included and the end is omitted.

like image 38
Russell Borogove Avatar answered Dec 08 '25 09:12

Russell Borogove



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!