Python program to find N largest elements from a list
Last Updated :
17 May, 2023
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 :
Python3
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)
list1 = [ 2 , 6 , 41 , 85 , 0 , 3 , 7 , 6 , 10 ]
N = 2
Nmaxelements(list1, N)
|
Output :
[85, 41]
Time Complexity: O(N * size) where size is size of the given list.
Auxiliary space: O(N)
Method 2:
Python3
l = [ 1000 , 298 , 3579 , 100 , 200 , - 45 , 900 ]
n = 4
l.sort()
print (l[ - n:])
|
Output
[298, 900, 1000, 3579]
Output:
[-45, 100, 200, 298, 900, 1000, 3579]
Find the N largest element: 4
[298, 900, 1000, 3579]
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Method 3: Using sort() and loop
Approach:
- Sort the given list
- Traverse the list up to N values and append elements in new array arr.
- Print the array arr.
Python3
l = [ 1000 , 298 , 3579 , 100 , 200 , - 45 , 900 ]
n = 4
l.sort()
arr = []
while n:
arr.append(l[ - n])
n - = 1
print (arr)
|
Output
[298, 900, 1000, 3579]
Time Complexity: O(n*logn)
Auxiliary Space: O(n), where n is length of list.
Please refer k largest(or smallest) elements in an array for more efficient solutions of this problem.
Approach #4: Using heapq
Initialize a heap queue using the input list. Use the heapq.nlargest() function to find the N largest elements in the heap queue. Return the result.
Algorithm
1. Initialize a heap queue using the input list.
2. Use the heapq.nlargest() function to find the N largest elements in the heap queue.
3. Return the result.
Python3
import heapq
def find_n_largest_elements(lst, N):
heap = lst
return heapq.nlargest(N, heap)
lst = [ 4 , 5 , 1 , 2 , 9 ]
N = 2
print (find_n_largest_elements(lst, N))
lst = [ 81 , 52 , 45 , 10 , 3 , 2 , 96 ]
N = 3
print (find_n_largest_elements(lst, N))
|
Output
[9, 5]
[96, 81, 52]
Time complexity: O(n log n), where n is the length of the input list due to building the heap.
Auxiliary Space: O(n), where n is the length of the input list, due to the heap queue.
Using numpy.argsort() function
note: install numpy module using command “pip install numpy”
Algorithm:
Convert the given list into a numpy array using np.array() function.
Use np.argsort() function to get the indices of the sorted numpy array in ascending order.
Use negative indexing and extract the last N indices from the sorted array.
Use the extracted indices to get the corresponding elements from the original numpy array.
Return the N maximum elements from the original list.
Python3
import numpy as np
def Nmaxelements(list1, N):
list1 = np.array(list1)
return list1[np.argsort(list1)[ - N:]]
list1 = [ 2 , 6 , 41 , 85 , 0 , 3 , 7 , 6 , 10 ]
N = 3
print (Nmaxelements(list1, N))
|
Output:
[10 41 85]
Time complexity:
Converting list to numpy array takes O(n) time, where n is the length of the list.
Sorting the numpy array using np.argsort() function takes O(nlogn) time.
Extracting the last N indices using negative indexing takes O(1) time.
Extracting the N maximum elements from the original list takes O(N) time.
Overall time complexity is O(nlogn).
Auxiliary Space:
The additional space required is to store the numpy array which takes O(n) space. Therefore, the space complexity is O(n).
Method : Using Sorted() + loop
Algorithm :
- A list of integers named “list” is initialized with the values [2, 1, 8, 7, 3, 0, 9, 4].
- An integer variable named “n” is initialized with the value 3. This variable specifies how many largest elements should be retrieved from the list.
- Two empty list variables, “res” and “list1”, are initialized.
- The original list is printed using the print() function and the “list” variable.
- The sorted() function is used to sort the list in descending order, and the sorted list is assigned to the “list1” variable.
- A for loop is used to iterate from 0 to n-1, and the first n elements of the sorted list are appended to the “res” list using the append() method.
- The sorted list is printed using the print() function and the “list1” variable.
- The n largest elements in the list are printed using the print() function, the number “n”, and the “res” list.
Python3
list = [ 2 , 1 , 8 , 7 , 3 , 0 , 9 , 4 ]
n = 3
res = []
list1 = []
print ( 'The given list is:' , list )
list1 = sorted ( list , reverse = True )
for i in range ( 0 , n):
res.append(list1[i])
print ( 'The sorted list is:' , list1)
print ( 'The ' , n, ' largest elements in the given list are:' , res)
|
Output
The given list is: [2, 1, 8, 7, 3, 0, 9, 4]
The sorted list is: [9, 8, 7, 4, 3, 2, 1, 0]
The 3 largest elements in the given list are: [9, 8, 7]
Time Complexity : O(n log n)
Auxiliary Space : O(n)
Similar Reads
Python Program to Find Largest Element in an Array
To find the largest element in an array, iterate over each element and compare it with the current largest element. If an element is greater, update the largest element. At the end of the iteration, the largest element will be found. Given an array, find the largest element in it. Input : arr[] = {1
4 min read
Python program to find second largest number in a list
In this article, we will explore various methods to find second largest number in a list. The simplest way to find is by using a loop. Using LoopUse a loop (for loop) to iterate over the list and keep two variables max1 and max2 to keep track of largest and second largest number of list. [GFGTABS] P
2 min read
Python | Indices of N largest elements in list
Sometimes, while working with Python lists, we can have a problem in which we wish to find N largest elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let's discuss a certain way to fi
5 min read
Python Program to Find Most common elements set
Given a List of sets, the task is to write a Python program tocompare elements with argument set, and return one with maximum matching elements. Examples: Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}], arg_set = {9, 6, 5, 3}Output : {9, 3, 5, 7}Explanation : Resultant
5 min read
Python | Find most frequent element in a list
Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python. Example Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we
2 min read
Python Program to Find Largest Item in a Tuple
We need to find the largest number or the top N largest numbers from a tuple. For Example: Input: (10,20,23,5,2,90) #tupleOutput: 90Explanation: 90 is the largest element from tuple There are several efficient ways to achieve this: Using max()max() in Python is the most efficient way to find the lar
4 min read
Python | Find top K frequent elements from a list of tuples
Given a list of tuples with word as first element and its frequency as second element, the task is to find top k frequent element. Below are some ways to above achieve the above task. Method #1: Using defaultdict C/C++ Code # Python code to find top 'k' frequent element # Importing import collection
5 min read
Python Program to Find k maximum elements of array in original order
Given an array arr[] and an integer k, we need to print k maximum elements of given array. The elements should printed in the order of the input.Note : k is always less than or equal to n. Examples: Input : arr[] = {10 50 30 60 15} k = 2 Output : 50 60 The top 2 elements are printed as per their app
3 min read
Python Program to Find maximum element of each row in a matrix
Given a matrix, the task is to find the maximum element of each row.Examples: Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56 Method 1: The idea is to run the loop for no_of_rows. Check each element inside the row and fin
5 min read
Python Program to get Maximum product of elements of list in a 2D list
Given a 2D list, we need to find the maximum product of elements for each list within the 2D list and determine which list yields the highest product. The goal is to efficiently compute the product of elements and identify the list with the maximum product. Using loop with prod from mathThis method
4 min read