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.

Recommended Answers

All 2 Replies

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)
commented: perfect, thanks! +3

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
ignore.add(3)

place, value = max_with_ignore(a, ignore)

print("With ignore indexes %s we got maximum in index %i, value %i in sequence:\n%s" % #\n is the new line character
      (ignore, place, value, a) # multiple lines because of parenthesis OK
      )
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.