jasmine
jasmine

Reputation: 361

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

Upvotes: 7

Views: 13772

Answers (3)

Chris
Chris

Reputation: 22953

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(flatten(l))) # 10

Upvotes: 3

Bijay Gurung
Bijay Gurung

Reputation: 1104

Could be shorter/better but 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))

Upvotes: 3

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

For finding the max value, iterating twice looks extra overhead to me. Firstly, for flattening the list and then again to find the max value. Here is the example to create a recursive function to return you the max value of the nested list in a single iteration as:

# 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

Sample run:

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

Upvotes: 1

Related Questions