Python Question

# Why all the lines of my 2d array take the value I pass to only one of them?

hello!

I am trying to run the following code recursively, where "vetor" is the current state of several variables and I am storing the first 50 in "matriz", a 2d array with 50 lines and 10 columns. Everything is initialized as zero.

What happens is that in the first iteration, the first line takes the value of the current "vetor". So far so good, but then in the second loop the "vetor" value is assigned to both the second AND the first line of "matriz". In the last iteration, for example, all lines of "matriz" are equal to the last value of "vetor".

I study control engineering and primarily program in C or MATLAB, so I am kinda newbie in Python...

Below, the part of the code described, where I believe the problem is.

``````            #armazena as variáveis do estado
vetor[0]=sc.get_ball_distance()
vetor[1]=sc.get_ball_angle()
vetor[2]=sc.get_target_angle()
vetor[3]=sc.get_obstacle_distance()
vetor[4]=sc.get_obstacle_angle()
vetor[5]=sc.get_spin()
vetor[6]=force_left_anterior
vetor[7]=force_right_anterior
vetor[8]=force_left
vetor[9]=force_right

#armazena o vetor de estado como linha na matriz
if cnt<50:
matriz[cnt]=vetor
cnt=cnt+1
``````

When you have an assignment `a = b` (`matriz[cnt]=vetor` in your case) in c/c++ the copy/asignment constructor is called and the content of the object is essentially copied. No matter whether the type of `a` is a primitive type like `int`/`float` or `struct`/`class` (i.e. `std::vector<T>`).

In python however the variables `a` and `b` are references to objects, like c++ references or c-pointers (but without the pointer dereferencing syntax).

The c-programmer might think that modifying `a` will not change `b`, but this is not the case in the following snippet

``````a = [1, 2, 3]
b = a
a.append(42)
print(b)
``````

will output `[1, 2, 3, 42]` because `a` and `b` are both references to the same object (in memory).

To solve this you need to explicitly copy `vetor` before assigning it to `matriz[cnt]`. Have a look at Shallow and deep copy operations. Deep copy is likely what you need.

Edit: If `vetor` is a `list` a simple constructor call will do the trick: `list(vetor)`

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download