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

1 Like

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]]
2 Likes

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!

6 Likes

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!

14 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. :wink:

4 Likes

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

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

Output: [0, 2, 3, 0, 2, 3, 0, 2, 3, 0, 2, 3, 0, 2, 3]

Im getting the [0,2,3] answer but 5 times?

can someone explain why im getting this output? dont we have to do a nested loop since there are two paramaters?

you have nested loops.

We don’t need nested loops. If we have two lists, and we want the first element of both lists we can do:

lst1[0]
lst2[0]

so we only need to generate the indexes/indices ones to retrieve values from both lists.

Hi stetim94:

I don’t quite understand how I can change a bit of my current code to get the correct answer?
This is what I originally input:

def same_values(lst1, lst2):
same_list =
for x in lst1:
for y in lst2:
if x == y:
mark = lst1.index(x)
same_list.append(mark)
return same_list

but my outcome was: [0, 0, 2, 3, 3]

any help would be great! Thank you so much

1 Like

I literally covers this in the answer you replied to? Using nested loops:

for x in lst1:
    for y in lst2:

isn’t going to work. Using .index() method is also a bad idea, this gives you the first match.

instead, you should use range() to generate indexes which you can use to get values from both lists at that index/position.

1 Like
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]]

Great solution! Simple and functional!