top of page

Python script to find out the maximum value in nested list

Kritika Rajput

In this post, you will learn about how to write the program to find out the maximum or minimum value in nested list.


So we can write the list in two different ways.

1- Flat list like it can contain integer, float or strings.

for example:- [11,'programmers door',3.5]

2- Nested list contain lists within the list.

for example:- [[1,2,3,4],10,20,[5,15]]


So in the flat list finding out the maximum value is simple we can use the max function or min function and we can find out the value easily but in the nested list it won't work.


Example of flat list:-

list1 = [2, 4, 6, 8, 10]
print(max(list1))   

Output:

10

Example of nested list:-


list1 = [[2,4],5,33,5]


Now if i save this and run this we will get the error because we can't compare the integers with the list type, so then, how to find out the maximum or minimum value in the nested list

We can convert the nested list to flat list first then we can use this max or min function as we know this max and min function won't work for the nested list, so we will convert the nested list of flat list first then we will apply that max or min function to find out the maximum or minimum value.


Program:

list2=[]
def get_max(list1):
    for i in list1:
        if type(i)==list:
            get_max(i)
        else:
            list2.append(i)
    return max(list2)

list1 = [10,11,[22,30,[50,35],13],66]
print(get_max(list1))

Output:

66
 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

14 views0 comments

Recent Posts

See All

Comments


bottom of page