-2

Given vector:

a=[6,7,8]
b=a[:]

desired result:

c=somefunction(b)
print(c)
[ 6  6  7  7  8  8]

here is my code that failed: I don't understand why this insert function doesn't update itself.

import numpy as np
def test3(x):
    a = x[:]
    b=np.array([])
    for i in range(0,len(a)):

            b=np.insert(a,i,a[i])

    return b

z=[8,9,10,11]
f=test3(z)
print(f)
[ 8  9 10 11 11]

Thank you so much for your attention.

AltunE
  • 375
  • 3
  • 10
  • 2
    Checkout [`np.repeat`](https://numpy.org/doc/stable/reference/generated/numpy.repeat.html). `np.repeat([6, 7, 8], 2)` -> `array([6, 6, 7, 7, 8, 8])` – Ch3steR May 28 '21 at 13:30
  • If you are using an IDE **now** is a good time to learn its debugging features Or the built-in [Python debugger](https://docs.python.org/3/library/pdb.html). Printing *stuff* at strategic points in your program can help you trace what is or isn't happening. [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – wwii May 28 '21 at 13:40
  • 1
    With each iteration you insert a value into `a` and assign the result to `b`. `a` never changes so subsequent iterations are always operating on the original/pristine `a`. [https://numpy.org/doc/stable/reference/generated/numpy.insert.html](https://numpy.org/doc/stable/reference/generated/numpy.insert.html). – wwii May 28 '21 at 13:44

2 Answers2

1

There is a function that does exactly what you want: read the doc

c = np.repeat(a, 2)                       
Hamza usman ghani
  • 2,264
  • 5
  • 19
Diego Palacios
  • 1,096
  • 6
  • 22
-1

Your example is confusing but I think you want the following result:

a=np.array([0,1,2])
b=np.array([10, 11, 12])
out = np.empty((a.shape[0]*2))
out[::2]=a
out[1::2]=b

Output:

>>> print(out)
[ 0. 10.  1. 11.  2. 12.]
lefevrej
  • 181
  • 1
  • 6