I figured out the for-loop solution but was trying to find and alternative using list comprehension… and failed. What’s wrong with this / what is the way? (error was list out of range). My sense is that the index object is looking for “i” rather than what I intend which is the first element of lst1 if it is the same as the first element of lst2.
svi = [lst1.index(i) for i in lst1 if lst1[i] == list2[i]]
your variable i contains value from the list, so trying to access by index (lst1[i]) will throw an index error when there is a value in the list which is higher then the highest index (which is quite common)
i wouldn’t use the .index() method, the index method always gives the first match, which is problematic if one value occurs multiple times in a list
def same_values(foo, bar):
return [index for index, value in enumerate(foo) if value == bar[index]]
Explanation:
The enumerate() method returns an enumerate object that contains (index, value) tuples of an iterator object, so we can use it with lists.
For example:
my_list = ['a', 'b', 'c']
for index, value in enumerate(my_list):
print(index, value)
> 0 'a'
> 1 'b'
> 2 'c'
So using the enumerate() method gives us a handy way to get the index and value pairs of a list. Now we can break down the problem into smaller steps:
foo = [1,2,3,5]
bar = [1,2,3,6]
same_values = []
for index, value in enumerate(foo):
if value == bar[index]:
same_values.append(index)
print(same_values)
> [0,1,2]
And finally, we can re-write the above snippet into list comprehension, shown at the top of this post.
def same_values(lst1, lst2):
equal_indices=[]
for indx1 in range(len(lst1)):
for indx2 in range(len(lst2)):
if lst1[indx1]==lst2[indx2] and indx1==indx2:
equal_indices.append(indx1)
return equal_indices
Why do we need two loop? Once we have an index, we can use this index to look up both values from the different lists at this index. This saves on the number of loop iterations and conditions you need.
And you can replace ‘range(len(lst1))’ with ‘range(smaller_lst)’ by adding an if conditional check at the beginning of the function which assigns the length of the shorter list to smaller_lst.
def same_values(lst1, lst2):
# The normal way
'''
ind = []
for i in range(len(lst1)):
if lst1[i] == lst2[i]:
ind.append(i)
return ind
'''
# As a list comprehension
return [i for i in range(len(lst1)) if lst1[i] == lst2[i]]