Introduction
In this challenge, you are tasked with writing a Python function that returns the n
minimum elements from a given list.
In this challenge, you are tasked with writing a Python function that returns the n
minimum elements from a given list.
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:
sorted()
function to sort the list in ascending order.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]
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.