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 # 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.
Auxiliary space: O(N)
Method 2:
Python3 # 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[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 # Python program to find N largest # element from given list of integers l = [1000,298,3579,100,200,-45,900] n = 4 l.sort() arr = [] while n: arr.append(l[-n]) n -= 1 print(arr) # This Code is contributed by Pratik Gupta
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) # Test the function with given inputs 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) # convert list to numpy array 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 # python program to find n largest elements in the given list # Initializing the list list = [2, 1, 8, 7, 3, 0, 9, 4] n = 3 res = [] list1 = [] # printing the original list print('The given list is:', list) # using sorted() list1 = sorted(list, reverse=True) for i in range(0, n): res.append(list1[i]) # list after sorting print('The sorted list is:', list1) # printing the n largest elements in the list print('The ', n, ' largest elements in the given list are:', res) # This code is contributed by SHAIK HUSNA
OutputThe 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 | 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 | 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.ExampleMake 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 f
2 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 fi
5 min read