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 Number in a List
Finding the largest number in a list is a common task in Python. There are multiple way to do but the simplest way to find the largest in a list is by using Python's built-in max() function: Using max()Python provides a built-in max() function that returns the largest item in a list or any iterable.
3 min read
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 | 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 | Top N pairs by Kth element from list
Sometimes, while working with data, we can have a problem in which we need to get the maximum of elements filtered by the Kth element of record. This has a very important utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using filter() + l
4 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 program to insert an element into sorted list
Inserting an element into a sorted list while maintaining the order is a common task in Python. It can be efficiently performed using built-in methods or custom logic. In this article, we will explore different approaches to achieve this. Using bisect.insort bisect module provides the insort functio
2 min read
Python Program to Print Largest Even and Largest Odd Number in a List
Auxiliary Given a list. The task is to print the largest even and largest odd number in a list. Examples: Input: 1 3 5 8 6 10 Output: Largest even number is 10 Largest odd number is 5 Input: 123 234 236 694 809 Output: Largest odd number is 809 Largest even number is 694 The first approach uses two
7 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 print element with maximum vowels from a List
Given a list containing string elements, the task is to write a Python program to print a string with maximum vowels. Input : test_list = ["gfg", "best", "for", "geeks"] Output : geeks Explanation : geeks has 2 e's which is a maximum number of vowels compared to other strings.Input : test_list = ["g
7 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