1

I'm trying to find the max value of a list or tuple that contains other lists or tuples. My first thought is to flatten it out and then use the max() function to find the maximum from the overall list, but I'm having difficulty doing that. Any suggestions?

An example is you have the tuple: (1, 2, 3, (1, 2)) and the expected output would be 3

Another example is the list [1, (2, 3), [4, 5]] and the output should be 5

This is take two using a flatten function and recalling it:

def flatten(t):
output = []
for item in t:
    if type(item) != type([]) or type(()):
        output.append(item)
    else:
        output.extend(flatten(item))
return output

def max_val(t):
    flatten(t)
    return max(output)
3

3 Answers 3

1

You can define a generic function to flatten your inputs using chain.from_iterable and collections.Iterable:

from itertools import chain
from collections import Iterable

x = (1, 2, 3, (1, 2))
y = [1, (2, 3), [4, 5]]

def flatten(x):
    return chain.from_iterable([i] if not isinstance(i, Iterable) else i for i in x)

res = max(flatten(x)) # 3

res = max(flatten(y)) # 5
1

You can make custom function to flatten your iterable and the use standard max or min functions:

from collections.abc import Iterable

x = (1, 2, 3, (1, 2))

def my_flatten(iterable):
    for value in iterable:
        if isinstance(value, Iterable):
            yield from my_flatten(value)
        else:
            yield value

print('min = ', min(my_flatten(x)))
print('max = ', max(my_flatten(x)))

Outputs:

min =  1
max =  3
1
  • btw isinstance('', Iterable) is True, i'm not sure if this is related to OP, but it's good to keep in mind Jul 15, 2018 at 17:58
0

You can use the package more_itertools to flatten what you have.

import more_itertools
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
res = list(more_itertools.flatten(lst))

Then you just need to use the max() function.

1
  • 1
    does this work for tuples as well? It says a tuple is not a callable item with that function Jul 15, 2018 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.