Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Find Largest Number in a List
Next article icon

Python program to find N largest elements from a list

Last Updated : 17 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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]

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:

  1. Sort the given list
  2. Traverse the list up to N values and append elements in new array arr.
  3. 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 :

  1. A list of integers named “list” is initialized with the values [2, 1, 8, 7, 3, 0, 9, 4].
  2. An integer variable named “n” is initialized with the value 3. This variable specifies how many largest elements should be retrieved from the list.
  3. Two empty list variables, “res” and “list1”, are initialized.
  4. The original list is printed using the print() function and the “list” variable.
  5. The sorted() function is used to sort the list in descending order, and the sorted list is assigned to the “list1” variable.
  6. 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.
  7. The sorted list is printed using the print() function and the “list1” variable.
  8. 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
 
 
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)



Next Article
Python Program to Find Largest Number in a List

S

SaumyaBansal
Improve
Article Tags :
  • Python
  • Python Programs
  • Technical Scripter
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences