Filter list's elements by type of each element
<p>I have list with different types of data (string, int, etc.). I need to create a new list with, for example, only int elements, and another list with only string elements. How to do it?</p>

<p>You can accomplish this with <a href="https://docs.python.org/3.5/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list  comprehension</a>:</p>

<pre><code>integers = [elm for elm in data if isinstance(elm, int)]
</code></pre>

<p>Where <code>data</code> is the data. What the above does is create a new list, populate it with elements of <code>data</code> (<code>elm</code>) that meet the condition after the <code>if</code>, which is checking if element is instance of an <code>int</code>. You can also use <a href="https://docs.python.org/3.5/library/functions.html#filter" rel="nofollow"><code>filter</code></a>:</p>

<pre><code>integers = list(filter(lambda elm: isinstance(elm, int), data))
</code></pre>

<p>The above will filter out elements based on the passed lambda, which filters out all non-integers. You can then apply it to the strings too, using <code>isinstance(elm, str)</code> to check if instance of string.</p>

python