Here, we learn how to find out the N largest and smallest elements from the list? Where, list and N given by the user, N may be any value but less than the list length.
Description:
There are two ways,
1. By defining a function:
Procedure:
- Define the function name largest_ele and smallest_ele.
- Pass two arguments in a function (l,n) : l is the list and n is the number of elements.
- Run the for loop n times
- In the loop find the maximum of the given list and append it to another list
- And after appending to another list remove the maximum element from the list
By the inbuilt module heapq module
If you are looking for the N smallest or largest items and N is small compared to the overall size of the collection, these functions provide superior performance.
- Import the heapq module
- Give the list
- Now use the function heapq.nlargest(n,l) and heapq.nsmallest(n,l) from the module to find the largest and the smallest numbers.
Python code:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer