1

I am trying to find the indices for all matching items between two lists of different lengths.

I created a list comprehension to compare the two lists:

my_list = ["a123", "b456", "c234", "a134", "d567", "e789", "c278"]
match_str = ["a1", "c2"]
mod_list = [i for i in my_list if any([j in i for j in match_str])]

where the output is
mod_list = ['a123', 'c234', 'a134', 'c278']

However, when I try to use this enumerate method to get the corresponding indices, I get an error message:

list_idx = [i for i, x in enumerate(my_list) if x == any([j in i for j in match_str])]
TypeError: argument of type 'int' is not iterable

I'm not sure what is creating the error.

Am I approaching this correctly, or is there a better method? (I'd like to do this without using a loop)

Community
  • 1
  • 1
WillaB
  • 420
  • 5
  • 12

1 Answers1

0

Its because of that your code are iterating over the i that is index ! you need to change it to x and remove x == :

>>> list_idx = [i for i, x in enumerate(my_list) if x == any([j in i for j in match_str])]
                                                                   ^

change it to :

>>> list_idx = [i for i, x in enumerate(my_list) if any([j in x for j in match_str])]
>>> list_idx
[0, 2, 3, 6]
Mazdak
  • 105,000
  • 18
  • 159
  • 188