creating numpy array with first and last elements different and all other elements the same
<p>I want to create the following type of array</p>

<pre><code>N = 5 # size of the array
eta = 2
a00 = 1 # first element of array
a0N = 3 # last element of array
# all entries should be 'eta' except the first and the last one
diag = [a00, eta, eta, eta, a0N] 
</code></pre>

<p>I know how to create array that has eta as all its entries as follows.</p>

<pre><code>diag = np.zeros(N) + eta
</code></pre>

<p>Will I be able to create what I want using 
<code>np.zeros(N)</code> or will I have to use a more low level constructor such as <code>numpy.ndarray</code>? . </p>

<p>I'm not aware of a built in method for this kind of array. This is a pretty standard way of doing it.</p>

<pre><code>N = 5 # size of the array
eta = 2
a00 = 1 # first element of array
a0N = 3 # last element of array

# make a vector of 'etas', then change the first and last element
diag = np.ones(N,)*eta
diag[0] = a00
diag[-1] = a0N 
</code></pre>

<p>Another workaround would be to make a list of the elements in your desired array. Then you can cast it as an array with np.array, as shown:</p>

<pre><code>list_diag = [a00] + [eta for i in range(N-2)] + [a0N]
diag = np.array(list_diag)
</code></pre>

<p>Note: the latter solution might look cute, but will be much slower as N gets larger. </p>

python numpy scipy