Python Program to find the largest element in array

In this simple python program, we find the largest element in an array. It's an Array-based python program.

To understand this example, you should have knowledge of the following Python programming topics:

How to find the largest elements in an array?

Based on the array concept in python programming, we need to find the largest elements in an array. An array is a collection of elements of the same data type accessed by a common index. In this solved python program, to find the largest element.

We take the first element in the array in a variable, then with the help of a for loopwe traverse till the end of the array and compare each element with the variable containing the first element. If we found a greater element than the first element using an if condition in python, swap the variable to that element. Finally, after all the iteration of for loop, we have the largest value in our variable.

For example, consider an array with 5 elements A = [ 2, 8, 4, 9, 5]; first, we take the 2 in a variable named 'x' the in for loop we compare x with 8. Change the value of x = 8 and again traverse through the loop using python language basics. Now we compare x with 4, and there is no change for x as 3 is less than 8. and so on. When the for loop in python gets to the end, x will be the largest element, which is 9.


STEP 1: Initialize an array called lar and add some values predefined into the array.

STEP 2: Assign the first element of the array to a variable called 'L'.

STEP 3: Use the for loop from zero to the length of an array using the len() and range() method in the python programming language.

STEP 4: Compare each element in the array with a variable using the if condition.

STEP 5: If the element is greater than the variable, then change it as the element.

STEP 6: Print, the largest element in the array, is that variable using print in python language. We use the str() method in python to convert the integer to string for printing.

Python Source Code

lar = [1, 3, 9, 4, 5];     
L = lar[0];      # assigning the first element to a variable
for i in range(0, len(lar)):    # looping to traverse till the end of array  
   if(lar[i] > L):    # use a if condition to compare and assign greater value to variable L
       L = lar[i];    
print("Largest element in array is : " + str(L));   


Largest element in array is : 9