LOOPS Same Values

Hi,

Would someone please help me.
Why does this?

def same_values(lst1,lst2):
return [lst1.index(x) for x in lst1 if lst2[lst1.index(x)] == x]
print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))

return this-

[0, 2, 3, 3]

The last value is a repeat, and I can’t work out why it does this. I have tried this same thing a few different ways, and the code above returns the fewest repeats.

Please ignore the indentation of the return that is an error related to formatting restrictions of this forum rather than something I have overlooked.

def same_values(lst1,lst2):
    return [lst1.index(x) for x in lst1 if lst2[lst1.index(x)] == x]

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

What’s the goal of this program? To output a list containing all of the values that are the same, and in the same locations? Using .index() seems to make this much more convoluted than it needs to be, if that’s the case. Try:

return [lst1[i] for i in range(len(lst1)) if lst1[i]==lst2[i]]
#return a list containing...
#at each index of lst1, if the value here is the same as the value in lst2's same index, the value

Alternatively, if the goal is to get the indexes at which the values are the same, swap lst1[i] in the comprehension output to i.

1 Like

It is the latter case(return the index at which the values are the same). Your suggestion worked as expected.
I appreciate your help, thanks a bunch.

I understand your point concerning the necessary complexity. Convoluted is precise.

Is there a simple reason for the repeat at the end of the original output? Or is it something that one might expect and should keep in mind?

1 Like

If I’m totally honest, I did a full trace of your code and was still unable to find the issue; perhaps someone more skilled than I will be able to explain it more effectively (since that was, in fact, your original question). Usually, though, when encountering such duplicates, something you’re looping over is referencing the wrong index.

1 Like

I think something similar cropped up a couple of days ago (I haven’t check this chunk of code so perhaps you can) but note that the .index() method returns only the first appearance of a particular element in a list so both the lst1 index and the lst2 index might not be what you think they are (so defo keep that in mind).

1 Like

Thanks for clarifying. 825orion’s answer also suggests this.

It is useful to know