Find the max of an array in Python
In this post, you will learn how to find the max of an array. Here, we have mentioned two ways to find the maximum value in an array (or list) in Python.
Find the max of an array using max() function
We can use the built-in max() function to find the maximum value of an array.
Syntaxmax(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
Parameters:
- iterable: An iterable like a list, tuple, etc. from which the maximum value is to be found. *arg1, arg2, args: Two or more arguments among which the maximum value is to be found.
- key (optional): A function that specifies a one-argument ordering function like str.lower.
- default (optional): A value to return if the iterable is empty.
Example to find the max of an array
# Example list
array = [1, 3, 5, 2, 4, 6]
# Find the maximum value
max_value = max(array)
print("The maximum value in the array is:", max_value)
Output of the above code:
The maximum value in the array is: 6
Find the max in an array using for loop
If we prefer to find the maximum value manually (without using the max() function), we can use a loop to iterate through the array and keep track of the maximum value found. Here’s an example:
# Example array
array = [1, 3, 5, 2, 4, 6]
# Initialize the maximum value with the first element of the array
max_value = array[0]
# Iterate through the array
for num in array:
if num > max_value:
max_value = num
print("The maximum value in the array is:", max_value)
Output of the above code:
The maximum value in the array is: 6
Related Articles
Trigonometric functions Python Numpy
Python convert dataframe to numpy array
Convert binary to decimal in Python
Multiply all elements in list Python
Multiply each element of a list by a number in Python
Python NumPy: Overview and Examples
Convert Python list to numpy array
numpy dot product
Python Pandas Plotting
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python take screenshot of specific window
Read data from excel file using Python Pandas
Quick Introduction to Python Pandas
Python requests GET method
Python Convert XML to CSV
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Bouncing ball game code in Python
Remove character from string Python
Python raise keyword