I have this loop that I wrote to find the smallest number in an arbutrary list:
arbitrary=[44,999,20,55,13,21]
smallest=None
for i in arbitrary:
if smallest is None:
smallest=i
elif smallest>i:
smallest=i
print(smallest)
When I run the code, it gives me the correct value. However, shouldn’t it be:
elif smallest<i:
smallest=i
When it checks to see if the next value is the smallest, it should be checking to see if i is smaller than the current i value. But running elif smallest <i gives me the largest value, 999
I think I’m missing something obvious about how the loop is iterating over arbitrary, but it’s just not clicking. What am I missing, and why does the original code work?
>Solution :
In plain english what your elif statement is saying is that IF the smallest number in that iteration of the loop is BIGGER than the i-value then it is no longer the smallest number. This gets replaced by the i value. using a print statement in the loop can help you troubleshoot to understand what’s happening.
arbitrary=[44,999,20,55,13,21]
smallest=None
for i in arbitrary:
print(smallest)
if smallest is None:
smallest=i
elif smallest>i:
smallest=i
print(smallest)
the output of this code
None
44
44
20
20
13
13