Hi, I'd like to find the maximum value in a list but be able to state certain exceptions. For example: if list A=[1,5,3,4] I want to say

``max(A) except index 1``

which would return '4' as the maximum value. Is there a way of doing this?

Thanks.

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by pyTony

Something like this could do it ...

``````listA = [1, 5, 3, 4]
# index to be excluded
index = 1

mx = 0
for ix, n in enumerate(listA):
if n > mx and ix != index:
mx = n

print(mx)``````
perfect, thanks!

Python has very flexible max function, which you can use with enumerate like above:

``````# put definition in function for reuse, put the definitions mainly in beginning of the file
def max_with_ignore(seq, not_these):
""" this function takes sequence and set (or less efficiently list) of exception indexes and
returns maximum among not ignored indexes as pair (index, value) """
return max(enumerate(seq), key=lambda x: (float('inf') if (x[0] in not_these) else x))

ignore = set([1])  # ignore the indexes in this list
a = [1, 5, 3, 4]   # small letter for variable names
ignore = set([1])
# put right infinity value instead of value depending if you use min or max
print(max(enumerate(a), key=lambda x: (float('inf') if (x[0] in ignore) else x)))
# -> (3, 4)
# we got the index in addition of value, which is often nice