Search code examples
pythonminbuilt-in

How do I return a list of the 3 lowest values in another list


How do I return a list of the 3 lowest values in another list. For example I want to get the 3 lowest values of this list:

in_list = [1, 2, 3, 4, 5, 6]
input: function(in_list, 3)
output: [1, 2, 3]

Solution

  • You can use heapq.nsmallest:

    >>> from heapq import nsmallest
    >>> in_list = [1, 2, 3, 4, 5, 6]
    >>> nsmallest(3, in_list)
    [1, 2, 3]
    >>>