Here are three ways to find the minimum and maximum values in an array using Python.

3 methods to find min and max

First, let’s create an example array:

my_array = [23, 45, 12, 56, 78, 34, 65, 32]

Method#1: Use 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 simply finds the minimum and maximum values in the my_array array and prints them to the console.

Minimum value: 12
Maximum value: 78


** Process exited - Return Code: 0 **
Press Enter to exit terminal
Advertisements

Method#2: Use For Loop

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
Advertisements

Method#3: Use Sort

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 takes 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

Related