pythonlistiteratormin

Printing Min1 and Min2 using Python


What am I missing in this code here so that it sets min1 and min2 to the two smallest numbers?

def test() : # do not change this line!
  list = [4, 5, 1, 9, -2, 0, 3, -5] # do not change this line!          
  min1 = list[0]
  min2 = list[1]
  #missing code here
  print(min1, min2)
  return (min1, min2) # do not change this line!
  # do not write any code below here  
test() # do not change this line!
  # do not remove this line!

Solution

  • List does not sort elements in it implicitly. You have sort the list with sort() function. So before you take min1 and min2 from list you have sort list using sort function, you can do that with nameofyourlist.sort() and also you are not assigning return value of test() to any variable so you can avoid that line. Your final code can be as below

    def test():
        list = [4, 5, 1, 9, -2, 0, 3, -5]
        list.sort()
        min1 = list[0]
        min2 = list[1]
        print(min1, min2)
    
    test()