How to find maximum number in 2d python list

I have a list in python like

my_list = [2,4,6,[5,10,3]] 

How can I find the maximum number (i.e. the program should return max as 10)?

thanks

+6
source share
3 answers

Flatten your list, and then you can use the built-in max() function:

 l = [2,4,6,[5,10,3]] def flatten(seq): for el in seq: if isinstance(el, list): yield from flatten(el) else: yield el print(max(flatten(l))) # 10 
+3
source

May be shorter / better, but in one way:

 my_list = [2,4,6,[5,10,3]] print(max(max(x) if isinstance(x, list) else x for x in my_list)) 
+1
source

To find the maximum value, repeating twice seems redundant to me. First, to flatten the list, and then to search for the maximum value. Here is an example of creating a recursive function to return the maximum value of a nested list in one iteration as follows:

 # The good thing is, you need not to worry about the level of depth # of the nested list, you can use it on any level of nested list def get_max(my_list): m = None for item in my_list: if isinstance(item, list): item = get_max(item) if not m or m < item: m = item return m 

Run Example:

 >>> my_list = [2,4,6,[5,10,3]] >>> get_max(my_list) 10 
+1
source

Source: https://habr.com/ru/post/1012456/


All Articles