 # How could I use list comprehension to solve this?

Hi all,

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]]
``````

Thanks for any help.

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

Thanks. Is there a way to use list comprehension to solve?

yes, there is. You could use `range()` to get the indexes/indices. That should help

The following approach uses list comprehensions, but it starts to get a bit messy…

``````def same_values(L1, L2):
return [k for k in range(min(len(L1), len(L2))) if L1[k] == L2[k]]
``````

This approach works too;

``````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.

Happy coding!

1 Like

Hello!

Here is the code I wrote using a list comprehension as a solution for this challenge:

``````new_list = [index for index in range(len(lst1)) if lst1[index] == lst2[index]]
``````

Hope this helps!

2 Likes

another option when running loop in loop:

``````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. 1 Like