Code adds multiple copies of each number

why isn’t this working :frowning:

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

you nested the loops, as a result, for each value in lst1, you will loop completely over lst2

this can result in problems when you have the same value multiple times in a list. Lets stick with this example:

same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5])

5 is a good example, 5 is twice in lst2, given how your code is currently written, for both fives in lst2, we will append the index of the 5 in lst2 to lst3

furthermore, the .index() method will give the first element it can find. This will result in more problems

do you understand the assignment? You only need to add the index to the result list (lst3) when the values at the same index of both lists is the same

idk but i always keep thinking of stupid complex solution which never work, when the solution was pretty simple and straight forward, i just created a for loop using range(len(lst)) and placed my if statement to compare the two lists inside the loop.

that is the challenge, to come up with a simple solution. Which is indeed difficult. Keep practicing, it will get easier.

2 Likes

thanks a ton for the help :smile: