In a list of lists how to get all the items except the last one for each list?
<p>So I have this list of lists. Each nested list has <code>n+1</code> element where the first element are floats and the last one is an integer. I need to get , for each nested list, all the floats (so n elements out of <code>n+1</code>). Which is the best way to achieve that?</p>

<p>For example:</p>

<pre><code>x = [[0.1, 0.2, 1], [0.4, 0.05, 16], [0.3, 0.3, 5]]
output = [[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]]
</code></pre>

<p>If you are <em>certain</em> the <code>int</code> will always be last, slicing is an option whereby you trim off the last element from every sub-list <code>sub</code> in <code>x</code> with <code>sub[:-1]</code> (<code>[:-1]</code> means grab all except the last element):</p>

<pre><code>out = [sub[:-1] for sub in x] # or sub[:2] if sub is always 3 elements long
print(out)
[[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]]
</code></pre>

<p>Alternatively, you can do this by iterating through the elements of <code>x</code>, iterating through each sub-element and evaluating if it is an instance of a <code>float</code>, i.e:</p>

<pre><code>out = [[i for i in sub if isinstance(i, float)] for sub in x]
</code></pre>

<p>This filters out any element the list <code>sub</code> which is a sub-list in <code>x</code> that isn't an instance of the <code>float</code> type. This operates <em>irregardless of positioning</em> so you could use it if the position of the <code>int</code> isn't always last:</p>

<pre><code>print(out)
[[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]]
</code></pre>

<p>Finally, for an <em>in-place</em> approach, <code>for</code> looping and <code>pop</code>ing is a viable option:</p>

<pre><code>for s in x: _ = s.pop()
</code></pre>

<p>Now <code>x</code> is mutated to:</p>

<pre><code>print(x)
[[0.1, 0.2], [0.4, 0.05], [0.3, 0.3]]
</code></pre>

python list python-3.x