Movatterモバイル変換


[0]ホーム

URL:


Open In App

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.

Python
arr=[10,324,45,90,9808]res=max(arr)print(res)

Output
9808

Using Iteration

This method manually traverse the array and update the largest element when a bigger element is found.

Python
arr=[10,324,45,90,9808]res=arr[0]foriinrange(1,len(arr)):ifarr[i]>res:res=arr[i]print(res)

Output
9808

Using reduce() Function

Thereduce() function from functools can find the largest element by applying max cumulatively across the array.

Python
fromfunctoolsimportreducearr=[10,324,45,90,9808]res=reduce(max,arr)print(res)

Output
9808

Using sort() Function

Heresort() function is used to sort the array. The largest element will be the last element of the sorted array.

Python
arr=[10,324,45,90,9808]arr.sort()res=arr[-1]print(res)

Output
9808

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.

Python
importoperatorarr=[2,1,7,3,0]res=0foriinarr:ifoperator.gt(i,res):res=iprint(res)

Output
7

Explanation:

  • Usesoperator.gt(a, b) which performs "a > b" comparison.
  • Iteratively updates res with the greater element.

Improve
Improve
Article Tags :

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp