How to keep every nth item in a list and make the rest zeros
<p>I am trying to model and fit to noisy data over a long time series and I want to see what happens to my fit if I remove a substantial amount of my data.</p>

<p>I have a long time-series of data and I am only interested in every nth item. However I still want to plot this list over time but with every other unwanted element removed.</p>

<p>For example, for n=4, the list</p>

<pre><code>a = [1,2,3,4,5,6,7,8,9,10...]
</code></pre>

<p>Should become</p>

<pre><code>a_new = [1,0,0,0,5,0,0,0,9,0...]
</code></pre>

<p>I don't mind if the <em>position</em> of the nth item is at the start or end of the sequence, my series is effectively arbitrary and so long that it won't matter what I delete. For example 'a_new' could also be:</p>

<pre><code>a_new = [0,0,0,4,0,0,0,8,0,0...]
</code></pre>

<p>Ideally the solution wouldn't depend on the length of the list, but I can have that length as a variable.</p>

<p>Edit 1:</p>

<p>I actually wanted empty elements, not zero's, (if that's possible?) so:</p>

<pre><code>a_new = [1,,,,5,,,,9...] 
</code></pre>

<p>Edit 2:</p>

<p>I needed to remove the corresponding elements from my time series too so that when everything is plotted, each data element has the same index as the time series element.</p>

<p>Thanks!</p>

<p>Use a <em>list comprehension</em> with a <a href="http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator"><em>ternary conditional</em></a> that takes the <code>mod</code> of each element on the number <code>n</code>:</p>

<pre><code>&gt;&gt;&gt; a = [1,2,3,4,5,6,7,8,9,10]
&gt;&gt;&gt; n = 4
&gt;&gt;&gt; [i if i % n == 0 else 0 for i in a]
[0, 0, 0, 4, 0, 0, 0, 8, 0, 0]
</code></pre>

<hr>

<p>In case the data does not proceed incrementally, which is most likely, use <code>enumerate</code> so the <code>mod</code> is taken on the index and not on the element:</p>

<pre><code>&gt;&gt;&gt; [v if i % n == 0 else 0 for i, v in enumerate(a)]
[1, 0, 0, 0, 5, 0, 0, 0, 9, 0]
</code></pre>

<p>The starting point can also be easily changed when using <code>enumerate</code>:</p>

<pre><code>&gt;&gt;&gt; [v if i % n == 0 else 0 for i, v in enumerate(a, 1)] # start indexing from 1
[0, 0, 0, 4, 0, 0, 0, 8, 0, 0]
</code></pre>

<hr>

<p>If you intend to <em>remove</em> your unwanted data rather than replace them, then a <em>filter</em> using <code>if</code> (instead of the ternary operator) in the list comprehension can handle this:</p>

<pre><code>&gt;&gt;&gt; [v for i, v in enumerate(a, 1) if i % n == 0]
[4, 8]
</code></pre>

python list