Javaexercise.com

Python Program To Find Max Value In List

To find a maximum element in an array in Python, we can use several ways such as loop to iterate the entire array and max() method of list.

Python does not have array concept instead uses the list to perform the task.

We maintain a variable called je_max and initialize it with the first element of the array. We then traverse through the array and compare each element with the max element one by one. If an element is greater than je_max, then we store the value of the element in je_max. When the loop terminates, je_max stores the largest value. Let's understand with an algorithm.

Algorithm To Find MAX Value in Python List

  1. Declare and initialize an array.

  2. Store first element in variable je_max.

  3. Loop through the array from 0 to the length of the array and compare the value of je_max with elements of the array.

  4. If any element is greater than je_max, je_max will hold the value of that element.

  5. At last, je_max will hold the largest element in the array.

Python Program To Find Max Value in an Array or List

Here, to find a maximum value from a list, we used for loop to traverse each element and compare until we find the desired result. This code is based on sequential search and requires more time to search if the array size is large. See the Python code below.

'''
Python program to find max element in array/list
'''
je_arr = [34, 131, 217, 735, 546];     
# Take a list     
je_max = je_arr[0];    
# Traverse each element using for loop
for i in range(0, len(je_arr)):    
    #Compare elements of array with max    
   if(je_arr[i] > je_max):    
       je_max = je_arr[i];    
           
print("Largest element present in the given array is: ", je_max);

Output:

Largest element present in the given array is: 735

 

Python Program To Find Max Value using max() method of List

Python provides a built-in method max() to find the largest elements from a list. We can use this for the same if don't want to write any custom code or loop. See the code below, we used a single line only to get the result.

'''
Python program to find max element in array/list
'''
# Take a list
je_arr = [34, 131, 217, 735, 546];     
# apply built-in max() method to get max value
max_val = max(je_arr)
           
print("Largest element present in the given array is: ", max_val);

Output:

Largest element present in the given array is: 735