How to find the largest element in an array in Python
Given an array with numerical values, the largest element can be found in multiple ways.
Solution
We can use solve this problem in the following ways in Python:
- Using a
for-inloop - Using
max() - Using
sort()
1. Using a for-in loop
- We will use a
for-inloop and a variable that stores the largest element to solve this. - Initialize a list
lstwith[20, 49, 1, 99]. - Initialize the
largestvariable with the first element in the list. - Use the
for-inloop to traverse every element in the list, and check if the current elementiis greater than the value present in thelargestvariable. - If it is, then assign the value in
ito the variablelargest. - After the loop ends,
largestwill store the largest element in the list.
#initialize listlst = [20, 49, 1, 99]#initialize largest with first elementlargest = lst[0]#traverse the arrayfor i in lst:if i>largest:largest = iprint(largest)
2. Using max()
We will use Python’s built-in function max() to solve this problem.
- We will pass the list
lstas a parameter to the functionmax(), which returns the largest element in the list.
#initialize listlst = [20, 49, 1, 99]#returns largest elementlargest = max(lst)#print largest in the listprint(largest)
3. Using sort()
We will use the sort() method to solve this.
- Initialize the list
lstwith[20, 99, 1, 49]. - Sort the list
lstwithlst.sort(), which sorts the original list in ascending order. - Since it is in ascending order, the last element
lst[-1]in the list is the largest. Print it.
#initialize listlst = [20, 99, 1, 49]#sort the listlst.sort()#print last element which is largestprint(lst[-1])