tags:

views:

111

answers:

4

Hello,

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 though of

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

But the last element is deleted from the list.

Thank for your help.

+1  A: 

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.

Russell Borogove
+3  A: 

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
adamk
+2  A: 
def eleMax(items, start=None, end=None):
    return max(items[slice(start, end)])
SilentGhost
Very interesting too :)
Natim
+1  A: 

When operating over large lists or many calls to this you can avoid the overhead of the slice creating a new list and copying the pointers.

http://docs.python.org/library/itertools.html#itertools.islice

Itertools contains islice which allows for iterating over the list in place without actually returning a new list for the slice.

from itertools import islice

def eleMax(items, start=None, end=None):
    return max(itertools.islice(items, start, end))

One current limitation is that negative values are not allowed for start, end, step.

kevpie