Here are the methods to find Array’s min and max values in Python. Python provides several built-in functions for working with arrays. One of the uses is finding array min and max values.
How to find Max and Min of Array in Python
First, let’s create an example array:
my_array = [23, 45, 12, 56, 78, 34, 65, 32]
1. Using min() and max() Functions
Python’s built-in min()
and max()
functions can be used to find the minimum and maximum values in an array.
For example:
#Python logic to find min and max of an array
my_array = [23, 45, 12, 56, 78, 34, 65, 32]
minimum = min(my_array)
maximum = max(my_array)
print("Minimum value:", minimum)
print("Maximum value:", maximum)
This code finds the minimum and maximum values in the my_array
array using the min()
and max()
functions, and prints them to the console. The output will look like this:
Minimum value: 12
Maximum value: 78
** Process exited - Return Code: 0 **
Press Enter to exit terminal
2. Using a Loop to Find Min and Max Values
Alternatively, you can find the minimum and maximum values in an array by using a loop to iterate over the array.
For example:
#Python logic to find min and max of an array
my_array = [23, 45, 12, 56, 78, 34, 65, 32]
minimum = my_array[0]
maximum = my_array[0]
for number in my_array:
if number < minimum:
minimum = number
if number > maximum:
maximum = number
print("Minimum value:", minimum)
print("Maximum value:", maximum)
This code initializes minimum
and maximum
to the first element in the array, then iterates over the array and updates the minimum
and maximum
values as needed. The resulting output will look like this:
Minimum value: 12
Maximum value: 78
** Process exited - Return Code: 0 **
Press Enter to exit terminal
3. Using the sort() Method to Find Min and Max Values
Another way to find the minimum and maximum values in an array is to use the sort()
method to sort the array in ascending or descending order, then take the first and last elements of the sorted array.
For example:
#Python logic to find min and max of an array
my_array = [23, 45, 12, 56, 78, 34, 65, 32]
my_array.sort()
minimum = my_array[0]
maximum = my_array[-1]
print("Minimum value:", minimum)
print("Maximum value:", maximum)
This code sorts the my_array
array in ascending order using the sort()
the method then assigns the minimum and maximum values to the first and last elements of the sorted array. The resulting output will look like this:
Minimum value: 12
Maximum value: 78
** Process exited - Return Code: 0 **
Press Enter to exit terminal
In conclusion, these are some ways to find the minimum and maximum values in an array using Python. Depending on your needs and preferences, you can choose the method that works best for you.
References