jasmine jasmine - 19 days ago 8
Python Question

How to find maximum number in a 2d python list

I have a list in python as

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


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

Thanks

Answer

Flatten your list, and then you can use the max() builtin 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(list(flatten(l)))) # 10