0

(This tag is similar to other tags, but the other tags are often specific). I tried to raise it on a high level.

I initialised a varibale "X", type(list) with an another varibale "arrayMetricPI", type(list) . But as I change ("X") I also change variable ("arrayMetricPI"), which doesn't make sense to me? Maybe it's Python specific?

What can I do, to keep an original value of a variable unchanged (here:"arrayMetricPI") - even if I change the initialised variable (here: "X")?

print(arrayMetricPI) # returns array "[0.0, 0.01, 0.02, 0.03,...]
X = arrayMetricPI

for xx in np.arange(0, counter, 1): 
# delete the first entry of the the array "X"

print(X)  # returns array "[0.01, 0.02, 0.03,...]
print(arrayMetricPI) # returns array "[0.01, 0.02, 0.03,...]

I expected that arrayMetricPI still starts with [0.0,...] as I just changed the list "X".

Max Mark
  • 71
  • 2
  • 9
  • `X = arrayMetricPI` makes them literally the same array; that doesn't make a copy. If `arrayMetricPI` is a numpy array, search for how to make a copy of it. Else, if it's a normal list, this is a duplicate of https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – Carcigenicate Jun 24 '19 at 23:46
  • That's expected. You've just given the same object two names. If a person sometimes went by "Mark" and sometimes went by "James", then anything that happens to Mark also happens to James. Same with your array. There's only one array, you've just given it two names. – mypetlion Jun 24 '19 at 23:47

3 Answers3

1

If your arrayMetricPI does not contain sublist, you can just X = arrayMetricPI[:].

If not, you will want to use copy.deepcopy

import copy
X = copy.deepcopy(arrayMetricPI)

Maybe it's Python specific?

I do not know how to say, here is one awesome description: Other languages have "variables", Python has "names"

LiuXiMin
  • 1,225
  • 8
  • 17
1

Lists are what's called Mutable objects.

You're encouraged to read up about it (not a very complicated subject), but in short -

When assigning things like x = some_list where some_list = [1, 4, 3], you're essentially saying "Now x will point to that list, and whoever else wants to point to it can also do so. Any changes made to any variable holding the list (for example, x) affect the actual list stored in memory".

Alon Emanuel
  • 172
  • 3
  • 10
0

Your second line makes X = arrayMetricPI, so you are changing the X value