In this python tutorial, you will learn how to Find Largest Element in an Array with the for loop, built in statements and operators of the python programming language.
How to Find Largest Element in an Array?
Let’s take a look at the source code, here the values are assigned in the code, the built in statements carry out the function.
RUN CODE SNIPPET#Python Program to Find Largest Element in an Array arr = [25, 11, 72, 85, 56]; max = arr[0]; for i in range(0, len(arr)): if(arr[i] > max): max = arr[i]; print("Largest element present in given array: " + str(max));
OUTPUT:
Largest element present in given array: 85
- At first we declare the variable
arr
with the values[25, 11, 72, 85, 56]
, after which we declare the first element of the array with the variablemax = arr[0]
- We declare a
for
loop where the range for the variablei
is(0, len(arr))
after which we declare anif
statement with the condition(arr[i] > max)
, followed by the declarationmax = arr[i]
- In the above code, we compare the elements of the array with the max variable, where if any element is greater than
max
, themax
variable will hold the value of that element - We declare a
print
function, which will display the statement("Largest element present in given array: " + str(max))
, where the variablemax
holds the final value.
NOTE:
- For loops are used to loop through an iterable object and perform the same action for each entry.
- The str() function converts values to a string form
- The if statement evaluates whether an expression is true. If a condition is true, the “if” statement is executed otherwise, it moves to the next statement.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string.
- The print statement is followed by a period, to initiate the format function.
- The print statement/string to be displayed in enclosed in double quotes.