R Thompson R Thompson - 2 months ago 7
Python Question

List comprehension confusion

I'm slightly confused by a problem that I'm having and wondered if anyone could help (it seems trivial in my mind so I hope that it genuinely is!)

Basically, I have filtered by a list via the following list comprehension:

depfilt = [s for s in department if 'author' not in s]


(where department had 154 elements and the resulting depfilt has 72 elements)

Now, I also had a separate list of iD values with 154 elements (
subj
), for which the indices of this list match those in
department
. I wanted to retain the correct iD values after the filtering process so used the following line of code:

subfilt = [s for s in subj if 'author' not in department[subj.index(s)]]


In my mind, I feel this should've worked, but subfilt is actually returning 106 list elements, rather than 72.

Does anybody have any idea why?

Thanks

Answer

Use enumerate instead of index in case of duplicate values

[s for i, s in enumerate(subj) if 'author' not in department[i]]