Move multiple elements (based on criteria) to end of list
<p>I have the following 2 Python lists:</p>

<pre><code>main_l = ['Temp_Farh', 'Surface', 'Heater_back', 'Front_Press',
'Lateral_Cels', 'Gauge_Finl','Gauge_Relay','Temp_Throw','Front_JL']
hlig = ['Temp', 'Lateral', 'Heater','Front']
</code></pre>

<p>I need to move elements from <code>main_l</code> to the end of the list if they contain strings listed in <code>hlig</code>.</p>

<p>Final version of <code>main_l</code> should look like this:</p>

<pre><code>main_l = ['Surface', 'Gauge_Finl','Gauge_Relay', 'Temp_Farh', 'Heater_back', 'Front_Press',
'Lateral_Cels', 'Temp_Throw','Front_JL']
</code></pre>

<p><strong>My attempt:</strong></p>

<p>I first try to find if the list <code>main_l</code> contains elements with a substring listed in the 2nd list <code>hlig</code>. Here is the way I am doing this:</p>

<pre><code>`found` = [i for e in hlig for i in main_l if e in i]
</code></pre>

<p><code>found</code> is a sublist of <code>main_l</code>. The problem is: now that I have this list, I do not know how to select the elements that do NOT contain the substrings in <code>hlig</code>. If I could do this, then I could add them to a list <code>not_found</code> and then I could concatenate them like this: <code>not_found + found</code> - and this would give me what I want.</p>

<p><strong>Question:</strong></p>

<p>Is there a way to move matching elements to end of the list <code>main_l</code>?</p>

<p>I would rewrite what you have to:</p>

<pre><code>main_l = ['Temp_Farh', 'Surface', 'Heater_back', 'Front_Press', 'Lateral_Cels', 'Gauge_Finl','Gauge_Relay','Temp_Throw','Front_JL']
hlig = ['Temp', 'Lateral', 'Heater','Front']

found = [i for i in main_l if any(e in i for e in hlig)]
</code></pre>

<p>Then the solution is obvious:</p>

<pre><code>not_found = [i for i in main_l if not any(e in i for e in hlig)]
answer = not_found + found
</code></pre>

<p>EDIT: Removed square brackets around list comprehension based on comments by Sven Marnach (to aviraldg's solution)</p>

python list python-2.7