Search code examples
pythonmin

How to find the second lowest number in a list in python


I wrote this code to find the second lowest number in a list, but I'm not getting the correct result. Can you show me what I did wrong ?

def second_lowest_number(list):
    
    the_minimum = min(list)
    new = []
    for i in range(len(t)):
        if list[i] > the_minimum:
            new.append(list[i])

    return min(new)

Solution

  • print(sorted(the_list)[1])
    

    I would think would work and would not be any slower than any other solution

    generally just keep it simple

    if it has duplicates just use a set

     print(sorted(set(the_list))[1]) 
    

    note that the first solution will fail if there is only one item in the list, and the second solution will fail if all items in the list are the same value