Given an array with numerical values, the largest element can be found in multiple ways.
We can use solve this problem in the following ways in Python:
for-in
loopmax()
sort()
for-in
loopfor-in
loop and a variable that stores the largest element to solve this.lst
with [20, 49, 1, 99]
.largest
variable with the first element in the list.for-in
loop to traverse every element in the list, and check if the current element i
is greater than the value present in the largest
variable.i
to the variable largest
.largest
will 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)
max()
We will use Python’s built-in function max()
to solve this problem.
lst
as a parameter to the function max()
, 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)
sort()
We will use the sort()
method to solve this.
lst
with [20, 99, 1, 49]
.lst
with lst.sort()
, which sorts the original list in ascending order.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])