# Python program to find N largest elements from a list

## Python program to find N largest elements from a list

Given a list of integers, the task is to find N largest elements assuming size of list is greater than or equal o N.

Examples :

Input : [4, 5, 1, 2, 9]
N = 2
Output :  [9, 5]

Input : [81, 52, 45, 10, 3, 2, 96]
N = 3
Output : [81, 96, 52]

A simple solution traverse the given list N times. In every traversal, find the maximum, add it to result, and remove it from the list. Below is the implementation :

 # Python program to find N largest # element from given list of integers   # Function returns N largest elements def Nmaxelements(list1, N):     final_list = []       for i in range(0, N):          max1 = 0                   for j in range(len(list1)):                  if list1[j] > max1:                 max1 = list1[j];                           list1.remove(max1);         final_list.append(max1)               print(final_list)   # Driver code list1 = [2, 6, 41, 85, 0, 3, 7, 6, 10] N = 2   # Calling the function Nmaxelements(list1, N)

Output :

[85, 41]

Time Complexity : O(N * size) where size is size of the given list.
Method 2:

 # Python program to find N largest # element from given list of integers   l = [1000,298,3579,100,200,-45,900] n = 4   l.sort() print(l[-n:])

Output:

[-45, 100, 200, 298, 900, 1000, 3579]
Find the N largest element: 4
[298, 900, 1000, 3579]

Last Updated on November 13, 2021 by admin

## Python hash() methodPython hash() method

Python hash() method Python hash() functionÂ is a built-in function and returns the hash value of

## Python program to print all even numbers in a rangePython program to print all even numbers in a range

Given starting and end points, write a Python program to print all even numbers in

## Python program maximum of threePython program maximum of three

Python program maximum of three Given three number a b and c, the task is

## Python program to implement Rock Paper Scissor gamePython program to implement Rock Paper Scissor game

Python program to implement Rock Paper Scissor game Python is a multipurpose language and one

## Accessing Attributes and Methods in PythonAccessing Attributes and Methods in Python

Accessing Attributes and Methods in Python Attributes of a class are function objects that define

## Pandas Dataframe.rename()Pandas Dataframe.rename()

Pandas Dataframe.rename() Pandas rename() method is used to rename any index, column or row. Renaming

## Python – Lemmatization with NLTKPython – Lemmatization with NLTK

Python | Lemmatization with NLTK Lemmatization is the process of grouping together the different inflected

## Pandas Series.str.find()Pandas Series.str.find()

Python – Pandas Series.str.find()   Pandas str.find() method is used to search a substring in