Question on not including a loop in a function

def same_values(lst1, lst2):
new_lst = []
  for index in range(len(lst1)):
    if lst1[index] == lst2[index]:
      new_lst.append(index)
  return new_lst

the instructions say to loop through the two lists so how come it looks like this code only loops through lst1 and does not have a for line written for lst2?

originally i had written:

def same_values(lst1, lst2):
  new_list = []
  for num in range(len(lst1)):
    for num in range(len(lst2)):
      if lst1[num] == lst2[num]:
        new_list.append(num)
  return new_list

this is from project 4 on this page: https://www.codecademy.com/courses/learn-python-3/articles/advanced-python-code-challenges-loops

You don’t need to loop through the indicies of both lists to find out if the numbers at those indicies match. Per the instructions, " 3. Loop through each index to the end of either of our lists".
(either being the operative word.)

2 Likes

If I understand the question correctly, we are to seek out matching values at corresponding indices. That means using only one loop:

if lst[index] == lst2[index]:
    result.append(index)

Now if we were looking for matching values anywhere in the lists then we would need to iterate both lists (nested loop), in which case we would have two different iteration variables, not one.

for i in a:
    for j in b:

Something to bear in mind for the future.

1 Like