I don't understand this coding

I know there is nothing wrong with the coding below, but I don’t understand the relationship between maximum and row[1]. How is possible that if row[1] > maximum, and at the same time row[1] == maximum. It might make sense to you, but not to me. Explain, please!

maximum = 0

for row in numerical_list:
if row[1] > maximum:
maximum = row[1]
most_common_name = row[0]
maximum == most_common_name

print(most_common_name)
print(maximum)

Where does it say

row[1] == maximum 

I only see

maximum = row[1] 

which is an assignment, not comparison.

Hi @falsaffar91. For the future, it’s a good idea to use the “preformatted text” option for code (the </> symbol in the editor, or use ``` before and after the code segment). That way it’s more readable, and the indentation is preserved, so we can tell what’s intended to be inside the loop. :slightly_smiling_face:

Anyway, to answer your question: in short, the value of maximum changes several times during the loop execution! You can think of the variable maximum as a “slot” where a value is stored, and when you assign it a value (like you do with maximum = row[1]), the value changes.

Note that, as the loop executes, the value of row[1] also changes (because each time row is the “next” element in the list).

So, taking this code (which is slightly modified from yours, to also print a few more things and give an initial value for the list):

numerical_list = [["a", 5], ["b", 2], ["c", 7]]
maximum = 0
most_common_name = "default"
print(most_common_name)
print(maximum)

for row in numerical_list:
    print(row)
    if row[1] > maximum:
        maximum = row[1]
    most_common_name = row[0]
    print(most_common_name)
    print(maximum)

This will print:

default   <-- this is before the loop executes
0         <-- also before the loop executes
["a", 5]  <-- first iteration of the loop
a
5
["b", 2]  <-- second iteration of the loop
b
5 
["c", 7]  <-- third iteration of the loop
c
7

So the final value of maximum is 7, but it changes several times over the execution of the code. It doesn’t happen at the same time that row[1] > maximum and row[1] == maximum, but those conditions both happen at different points during the execution.

Hope this makes some sense!

3 Likes