Iteration Variable in For-Loops

Hi team,

In this exercise, I just found out that the naming of the iteration variable plays an important role in achieving the desired output. The output that we want is to display the indices of both lists (lst1 and lst2) that contains the same element when compared. Please see the function I created below:

#Write your function here
def same_values(lst1, lst2):
  new_lst = []
  for x in range(len(lst1)):
    for x in range(len(lst2)):
      if lst1[x] == lst2[x]:
        new_lst.append(x)
    return new_lst
        
#Uncomment the line below when your function is done
print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))

The result of this function is (FYI this is the correct answer)

[0, 2, 3]

But, when I do the following, which is changing the name of the second iteration variable in the second For-Loop.

#Write your function here
def same_values(lst1, lst2):
  new_lst = []
  for x in range(len(lst1)):
    for y in range(len(lst2)):
      if lst1[x] == lst2[y]:
        new_lst.append(x)
    return new_lst
        
#Uncomment the line below when your function is done
print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))

The result is as follow (the wrong one)

[0, 0]

So my question is how does the computer read the two code differently? I tried to figure out the logic behind this but not getting there yet.

I would appreciate any help that I can get

Jimmy

Well, you don’t really need two loops. You could use the index generated by the loop to access both elements in the list

I would highly recommend running your code here:
http://www.pythontutor.com/visualize.html

which allows you to step through your code

Okay. Look at the placement of your return. Its nested within the outer loop. So the outer loop only makes a single iteration. The inner loop makes all its iterations

The first example works because the x (loop iterator) of the outer loop isn’t used. You use the loop iterator generated by the second loop. Making the outer loop redundant.

the second example doesn’t work, because x just remains zero while the inner loop makes its iterations. So you compare the first value of lst1 to all the values of lst2.

The outer loop never starts its second iteration, because return keyword is reached, which will hand back data to the caller, signaling the function is done executing.

1 Like

Hi @stetim94,

Thanks so much for explaining this to me. I really appreciate the effort. Now I kinda get the logic :slight_smile:
Plus, just saved the link you sent here… This might be useful for future projects.