Given an array, we need to find the largest element in it.
For example:
Input : arr[] = {20, 10, 20, 4, 100}
Output : 100
Let's explore different methods to find the largest element:
Using Built-in max() Function
Python has an inbuilt methodmax() which returns the maximum value among the arguments.
Pythonarr=[10,324,45,90,9808]res=max(arr)print(res)
Using Iteration
This method manually traverse the array and update the largest element when a bigger element is found.
Pythonarr=[10,324,45,90,9808]res=arr[0]foriinrange(1,len(arr)):ifarr[i]>res:res=arr[i]print(res)
Using reduce() Function
Thereduce() function from functools can find the largest element by applying max cumulatively across the array.
Pythonfromfunctoolsimportreducearr=[10,324,45,90,9808]res=reduce(max,arr)print(res)
Using sort() Function
Heresort() function is used to sort the array. The largest element will be the last element of the sorted array.
Pythonarr=[10,324,45,90,9808]arr.sort()res=arr[-1]print(res)
Please refer complete article onProgram to find largest element in an array for more details!
Using operator.gt()
Use the operator.gt() function to compare elements and find the largest element iteratively.
Pythonimportoperatorarr=[2,1,7,3,0]res=0foriinarr:ifoperator.gt(i,res):res=iprint(res)
Explanation:
- Usesoperator.gt(a, b) which performs "a > b" comparison.
- Iteratively updates res with the greater element.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice