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
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.
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.
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.
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.
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
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))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With