How to keep specific element indexs in an array
<p>Suppose I have two arrays:</p>

<pre><code>a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
b = [2,5,7]
</code></pre>

<p>And I want to keep the elements indexed in a that are listed in b so the 2nd, 5th and 7th index of a:</p>

<pre><code>a_new = [4, 25, 49]
</code></pre>

<p>I will then plot b against a_new / perform analysis on it.</p>

<p>For my application, a is a long series of simulated data, and b is a time series of when I want to sample from this data.</p>

<p>Thanks</p>

<p>There are two possible problems that you may be encountering, both of which have been somewhat mentioned in the comments. From what I see, you either have a problem reading the or you have an invalid index in <code>b</code>.</p>

<p>For the former, you may actually want</p>

<pre><code>a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
b = [2,5,7]
</code></pre>

<p>To produce:</p>

<pre><code>a_new = [9, 36, 64]
</code></pre>

<p>Since you always count starting from zero:</p>

<pre><code>[1, 4, 9, 16, 25, 36, 49, 64, 81]
 0  1  2  3   4   5   6   7   8
</code></pre>

<p>Hence, leading to an <a href="http://xyproblem.info/" rel="nofollow">XY problem</a>, where you try to solve a problem <em>your way</em> which is the wrong way. Therefore, it wastes our time to try to fix a problem that doesn't work since it is actually something else.</p>

<p>However, for the latter, you may have an anomaly in your <code>b</code> list. The way to index the list (given in the comments) as you wanted is using <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p>

<pre><code>a_new = [a[i-1] for i in b]
</code></pre>

<p>What this does is:</p>

<pre><code>a_new = []
for i in b:
    a_new.append(a[i-1])
</code></pre>

<p>Hence, when <code>i</code> is larger than or equal to <code>len(a)</code>, it evaluates to an invalid index:</p>

<pre><code>&gt;&gt;&gt; a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
&gt;&gt;&gt; len(a)
9
&gt;&gt;&gt; a[9]
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
IndexError: list index out of range
</code></pre>

python arrays list indexing