i was running a program that return the maximum 2 number in a certain list
and I found that there a difference between using if and elif in definition of function
So if i used :
def maxi (lst) :
max_pos1 = 0
max_pos2 = 1
if lst[max_pos1] < lst [max_pos2] :
max_pos1 , max_pos2 = 1 , 0
for x in range (len(lst)) :
if lst[max_pos1] < lst [x] :
max_pos1 , max_pos2 = x , max_pos1
if lst [max_pos2] < lst [x] :
max_pos2 = x
return lst[max_pos1] , lst[max_pos2]
lst = [1,2,3,4,5,6,7,8,9,10,11,12,77,14,15,16]
print(maxi(lst))
The output will be :
(77, 77)
Which is not correct in my opinion
but if i changed if in the 9 line to elif as follow :
def maxi (lst) :
max_pos1 = 0
max_pos2 = 1
if lst[max_pos1] < lst [max_pos2] :
max_pos1 , max_pos2 = 1 , 0
for x in range (len(lst)) :
if lst[max_pos1] < lst [x] :
max_pos1 , max_pos2 = x , max_pos1
elif lst [max_pos2] < lst [x] :
max_pos2 = x
return lst[max_pos1] , lst[max_pos2]
lst = [1,2,3,4,5,6,7,8,9,10,11,12,77,14,15,16]
print(maxi(lst))
The output will be :
(77, 16)
which the result i hoped for , can any one explain why this change happened in the output ?