list index comparison in python
comparison, indexing, list, python
Solution
You can use list comprehension to get the matching indices like this
list1, list2 = [1, 2, 3], [1, 4, 3]
print [index for index, (e1, e2) in enumerate(zip(list1, list2)) if e1 == e2]
Output
[0, 2]
We are first zipping both the lists with `zip`. So, on every iteration, we will get elements at corresponding positions from both the lists. And then we run it with `enumerate` which will return a tuple with the index and the actual element from the iterable. We retain the index, if the elements match.
Edit: For the particular input given by you in the comments section
list1, list2 = ["a", "b", "c", "d", "e"], ["e", "d", "c", "b", "a"]
print [index for index, (e1, e2) in enumerate(zip(list1, list2)) if e1 == e2]
Output
[2]
Problem
By list index comparison I mean that I have two lists which I sorted using different methods (bubblesort and insertion sort) according to 2 different criteria. I would now like to compare if an element in one of the list is in the same position in the other list and if so return its position. So for I have ``` List1 = selectionsort() List2 = bubblesort() indices = [List1.index(i) for i in List2] print (str(indices)) ``` I know this is not right because it compares the elements of List1 to List2 elements and returns the positions at which they match (i think). Furthermore this sort of implies that List1 is a subset of List2, which it is not, the two list are the same just ordered differently