Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find maximum number in a 2d python list

Tags:

python

list

max

2d

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

like image 452
jasmine Avatar asked Nov 18 '16 15:11

jasmine


People also ask

How do you find the maximum value of a 2D array?

In line 5, we use the amax() method to find the maximum value in the array. Then, we print the maximum value in line 6. From lines 8 to 12, we define a numpy 2D array. In lines 14 and 15, we use the amax() method to find the maximum across the row and column respectively.

How do I get the size of a 2D list in Python?

To get the length of a 2D Array in Python: Pass the entire array to the len() function to get the number of rows. Pass the first array element to the len() function to get the number of columns. Multiply the number of rows by the number of columns to get the total.

How do you find the largest number in a two dimensional array in Python?

You can find the maximum value in the entire array using the same numpy. max() method just like you have used in finding the max in 1D. It will find the lowest element and gives the output.

How do you find the max value in a list in Python?

The max() Function — Find the Largest Element of a List. In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.


3 Answers

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
like image 192
Christian Dean Avatar answered Oct 16 '22 19:10

Christian Dean


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))
like image 3
Bijay Gurung Avatar answered Oct 16 '22 20:10

Bijay Gurung


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
like image 1
Moinuddin Quadri Avatar answered Oct 16 '22 19:10

Moinuddin Quadri