N Minimum Elements

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this challenge, you are tasked with writing a Python function that returns the n minimum elements from a given list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13695{{"`N Minimum Elements`"}} python/booleans -.-> lab-13695{{"`N Minimum Elements`"}} python/lists -.-> lab-13695{{"`N Minimum Elements`"}} python/tuples -.-> lab-13695{{"`N Minimum Elements`"}} python/function_definition -.-> lab-13695{{"`N Minimum Elements`"}} python/default_arguments -.-> lab-13695{{"`N Minimum Elements`"}} python/build_in_functions -.-> lab-13695{{"`N Minimum Elements`"}} end

N Minimum Elements

Write a function called min_n(lst, n = 1) that takes in a list lst and an optional integer n (default value of 1). The function should return a new list containing the n smallest elements from the original list lst. If n is not provided, the function should return a list containing the smallest element from lst.

If n is greater than or equal to the length of lst, the function should return the original list sorted in ascending order.

Your function should accomplish this by following these steps:

  1. Use the built-in sorted() function to sort the list in ascending order.
  2. Use slice notation to get the specified number of elements.
  3. Return the resulting list.
def min_n(lst, n = 1):
  return sorted(lst, reverse = False)[:n]
min_n([1, 2, 3]) ## [1]
min_n([1, 2, 3], 2) ## [1, 2]

Summary

In this challenge, you learned how to write a Python function that returns the n minimum elements from a given list. You also learned how to use the built-in sorted() function and slice notation to accomplish this task.

Other Python Tutorials you may like