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:
Minimum element left from the array after performing given operations
Next article icon

Program to print N minimum elements from list of integers

Last Updated : 17 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Our task is to extract the smallest N elements from a list of integers.

For example, if we have a list [5, 3, 8, 1, 2] and want the smallest 3 elements, the output should be [1, 2, 3]. We’ll explore different methods to achieve this.

Using heapq.nsmallest

This method uses the nsmallest() function from the heapq module, which is optimized for finding the smallest elements efficiently.

Python
import heapq  # Input list a = [5, 3, 8, 1, 2]  # Number of smallest elements to extract n = 3  # Extract N smallest elements res = heapq.nsmallest(n, a) print(res)   

Output
[1, 2, 3] 

Explanation:

  • heapq.nsmallest function efficiently extracts the n smallest elements from the list using a heap-based algorithm.
  • This method is both fast and straightforward, making it the most efficient for this task.

Let’s explore some more methods and see how we can print N minimum elements from a list of integers in Python.

Table of Content

  • Using sorted
  • Using for loop

Using sorted

We can sort the list using the sorted() function and then use slicing to get the first n elements.

Python
# Input list a = [5, 3, 8, 1, 2] # Number of smallest elements to extract n = 3 # Sort the list and take the first N elements res = sorted(a)[:n] print(res)  

Output
[1, 2, 3] 

Explanation:

  • sorted() function sorts the entire list in ascending order.
  • By slicing the first n elements, we get the smallest values.
  • While simple, this method is less efficient for large lists as it involves sorting the entire list.

Using for loop

This method involves manually iterating through the list using a for loop to find the n smallest elements.

Python
# Input list a = [5, 3, 8, 1, 2]  # Number of smallest elements to extract n = 3  # Initialize an empty list to store the smallest elements res = []  # Make a copy of the original list to avoid modifying it b = a[:]  # Extract N smallest elements one by one for _ in range(n):     smallest = min(b)     res.append(smallest)     b.remove(smallest) print(res)   

Output
[1, 2, 3] 

Explanation:

  • We use the min() function to repeatedly find and remove the smallest element from the list.
  • The process is repeated n times to extract the required number of smallest elements.
  • This method is the least efficient due to the repeated scanning and modification of the list.


Next Article
Minimum element left from the array after performing given operations

S

SaumyaBansal
Improve
Article Tags :
  • Arrays
  • DSA
  • Python
  • School Programming
  • Technical Scripter
  • Python list-programs
  • python-list
  • school-programming
Practice Tags :
  • Arrays
  • python
  • python-list

Similar Reads

  • Closest numbers from a list of unsorted integers
    Given a list of distinct unsorted integers, find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all. Examples: Input : arr[] = {10, 50, 12, 100}Output : (10, 12)The closest elements are 10 and 12Input : arr[] = {5, 4, 3, 2}Output
    11 min read
  • Program to find the minimum (or maximum) element of an array
    Given an array, write functions to find the minimum and maximum elements in it. Examples: Input: arr[] = [1, 423, 6, 46, 34, 23, 13, 53, 4]Output: Minimum element of array: 1 Maximum element of array: 423 Input: arr[] = [2, 4, 6, 7, 9, 8, 3, 11]Output: Minimum element of array: 2 Maximum element of
    14 min read
  • Minimum element left from the array after performing given operations
    Given an array arr[] of N integers, the task is to remove the elements from both the ends of the array i.e. in a single operation, either the first or the last element can be removed from the current remaining elements of the array. This operation needs to be performed in such a way that the last el
    3 min read
  • Minimum product pair an array of positive Integers
    Given an array of positive integers. We are required to write a program to print the minimum product of any two numbers of the given array. Examples: Input: 11 8 5 7 5 100Output: 25 Explanation: The minimum product of any two numbers will be 5 * 5 = 25. Input: 198 76 544 123 154 675 Output: 7448Expl
    12 min read
  • Min sum of set of positive integers so that sum of no two elements is K
    Given two positive integers N and K. Create a set of size N containing distinct positive integers such that the sum of no two integers is K, the task is to find the minimum possible sum of the set that meets the above criteria. Since the answer may be large, print it modulo 10^9+7. Note: It is guara
    6 min read
  • Minimum product of k integers in an array of positive Integers
    Given an array arr[] containing n positive integers and an integer k. Your task is to find the minimum possible product of k elements of the given array. Examples: Input: arr[] = [198, 76, 544, 123, 154, 675], k = 2Output: 9348Explanation: We will choose two smallest numbers from the given array to
    7 min read
  • K-th smallest element after removing some integers from natural numbers
    Given an array arr[] of size 'n' and a positive integer k. Consider series of natural numbers and remove arr[0], arr[1], arr[2], ..., arr[n-1] from it. Now the task is to find k-th smallest number in the remaining set of natural numbers. If no such number exists print "-1". Examples : Input: arr[] =
    4 min read
  • For each value in [1, N] find Minimum element present in all Subarray of that size
    Given an array A[] of size N, the task is to find the minimum element present in all subarrays for all sizes from 1 to N where all the elements in the array are in range 1 to N Examples: Input: A[ ] = {1, 2, 3}Output: [-1, 2, 1]Explanation: All subarrays of size 1 {{1}, {2}, {3}} there is no common
    15+ min read
  • Minimum integer required to do S ≤ N*X
    Given an array A[] of size N. Let us denote S as the sum of all integers present in the array. Among all integers present in the array, find the minimum integer X such that S ≤ N*X. Examples: Input: N = 3, A[] = [1, 2, 3]Output: 2Explanation: Total sum of the array is 6, let's check for all the numb
    8 min read
  • Minimum number of elements to add to make median equals x
    A median in an array with the length of n is an element which occupies position number (n+1)/2 after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the n
    11 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