Removing characters from indices within multiple lists
<p>Just a really quick question I cannot figure out for the life of me, although it seems simple...</p>

<p>How do I delete the last 2 characters of each 4th index of a list, in a list? So in less confusing terms:</p>

<pre><code>f = ['yes', 'no', 'tot', 'foop\n']
p = ['ick', 'throw', 'tamp', 'lap\n']

L = []

L.append(f)
L.append(p)
</code></pre>

<p>So now L is:</p>

<pre><code>L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']]
</code></pre>

<p>How would I go about getting writing a loop that would get rid of the \n at the end of every 4th index, within both lists (that could also be extended for more than just the 2 lists I have above in the list)? </p>

<p>I just want it to re-return L, without those \n's at the end of those last indices. </p>

<p>As already mentioned in comments:</p>

<pre><code>f = ['yes', 'no', 'tot', 'foop\n']
p = ['ick', 'throw', 'tamp', 'lap\n']

L = []

L.append([item.strip() for item in f])
L.append([item.strip() for item in p])
</code></pre>

<p>Or in one step:</p>

<pre><code>f = ['yes', 'no', 'tot', 'foop\n']
p = ['ick', 'throw', 'tamp', 'lap\n']

L = []

for lst in [f, p]:
    L.append([item.strip() for item in lst])
</code></pre>

<p>Or shorter:</p>

<pre><code>f = ['yes', 'no', 'tot', 'foop\n']
p = ['ick', 'throw', 'tamp', 'lap\n']

L = [[item.strip() for item in l] for l in [f, p]]
</code></pre>

<p>Last but not least, literally answering your question; if you need to <em>specifically</em> strip certain indices from a list of lists:</p>

<pre><code>L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']]
for lst in L:
    lst[3] = lst[3].strip()
</code></pre>

<p>By default, <code>strip()</code> strips from whitespace characters, see <a href="http://www.tutorialspoint.com/python/string_strip.htm" rel="nofollow">this</a>.</p>

python list