List comprehension confusion
<p>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!)</p>

<p>Basically, I have filtered by a list via the following list comprehension:</p>

<pre><code>depfilt = [s for s in department if 'author' not in s]
</code></pre>

<p>(where department had 154 elements and the resulting depfilt has 72 elements)</p>

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

<pre><code>subfilt = [s for s in subj if 'author' not in department[subj.index(s)]]
</code></pre>

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

<p>Does anybody have any idea why?</p>

<p>Thanks</p>

<p>If <code>department</code> and <code>subj</code> are definitely in the same order ie. corresponding elements of each match up, then use <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a> to iterate over both lists simultaneously:</p>

<pre><code>[(d, s) for d, s in zip(department, subject) if 'author' not in d]
</code></pre>

<p>(using <code>d</code> for department and <code>s</code> for subject).</p>

<p>And this way you don't need to reference each element by index. Just standard iteration.</p>

<p>Edit: If you want keep lists separate then you can do the first step for <code>dept</code> as you already have and then modify the second loop for subject like so, still filtering against 'author' while looping over both:</p>

<pre><code>[s for d, s in zip(department, subject) if 'author' not in d]
</code></pre>

<p>(so the value of <code>d</code> is ignored in the 2nd loop)</p>

<p>Example of output:</p>

<pre><code>&gt;&gt;&gt; department = ['something', 'else', 'author', 'okay']
&gt;&gt;&gt; subject = ['some_subj', 'else_subj', 'author_subj', 'okay_subj']
&gt;&gt;&gt; [(d, s) for d, s in zip(department, subject) if 'author' not in d]
[('something', 'some_subj'), ('else', 'else_subj'), ('okay', 'okay_subj')]
&gt;&gt;&gt;
&gt;&gt;&gt; # and if you MUST do them seprately:
... [s for s in department if 'author' not in s]  # that's your `deepfilt`
['something', 'else', 'okay']
&gt;&gt;&gt; [s for d, s in zip(department, subject) if 'author' not in d]  # this is for `subfilt`
['some_subj', 'else_subj', 'okay_subj']
</code></pre>

python