smallest = None print("Before:", smallest) for itervar in [3, 41, 12, 9, 74, 15]: if smallest is None or itervar < smallest: smallest = itervar break print("Loop:", itervar, smallest) print("Smallest:", smallest)
break statement inside the loop will cause the loop to break in its first iteration regardless of the condition, so it won’t iterate through the entire list.
How can something be smaller than none?
That doesn’t work.
If you remove the
break line and run the code, you may find the code in fact does work. But if the line
if smallest is None or itervar < smallest:
is changed in order to reverse the order of the two conditions:
if itervar < smallest or smallest is None:
a TypeError will be raised!
Please refrain from posting images of code and instead post the code itself and put it into a code block. This forum utilizes syntax highlighting for all kinds of popular languages, including Python. It makes it much easier to test, and modify, your code, as needed.
And it’s fine if you want to post a solution, but you should also mark it a spoiler and explain your reasoning behind the code, including what you modified. It doesn’t benefit anyone to just post a solution with no context behind it.
L = [3, 41, 12, 9, 74, 15] smallest = None print("Before:", smallest) smallest = L for itervar in L[1:]: if itervar < smallest: smallest = itervar print("Loop:", itervar, smallest) print("Smallest:", smallest) print() print("Smallest:", min(L))
The first in the list L is declared to be the current smallest, so it is compared with the next member in the list. If the next is smaller, it is then declared to be the current smallest, and so on, until all members of list L have been examined. Upon completion, the current smallest will be the smallest of all members of list L.
Without a loop, it is easy to determine the smallest member of the list L, using the function min(L).
In Python, one problem can be solved in several ways, such as:
from functools import reduce L = [3, 41, 12, 9, 74, 15] smallest = reduce(lambda x, y: x if x<y else y, L) print("Smallest:", smallest)
reduce function is imported from the
functools module :
from functools import reduce
reduce has as the first argument some function with which we perform calculations with the members of the list and as the second argument the list itself. Here, using the abbreviated
x if x<y else y
it was determined which of the two current values is the smallest, within the
lambda x, y: x if x<y else y
So, the first two members are compared, and then the smaller of them is compared to the third member of the list. Then again the smallest with the fourth member of the list and so on until the last member of the list L.
Instead of comparing members, we could, for example, multiply them all:
product = reduce(lambda x, y: x*y, L)
Or to add them for example:
add = reduce(lambda x, y: x+y, L)