Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this work? Shouldn't it return the smallest value?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading