0

I'm on python 3.7.9.

-I need to copy some items from a list into another list.

-Then I need to do calculations on My new list without changing the original list.

But but whatever I do, my original list undergoes the same modifications that are done to my new list.

Could someone explain me Why ?

Thank's for your reply

Debugging mode: enter image description here

Mohamed Bdr
  • 967
  • 3
  • 9
  • 20
Snakes
  • 5
  • 1

2 Answers2

1

This phenomenon is termed as shallow copy in python.

Basically,

 reduite=mat[1:]

is taking references of the inner objects(which are again arrays) of mat, hence modifying the copy array reflects on the original.

Use deepcopy to solve this.

Samsul Islam
  • 2,581
  • 2
  • 17
  • 23
0

In your code, you are make the assignment:

reduite = mat[1:]

This only binds reduite to the elements of mat.

In other words, the variable now references to the same objects in memory, which is why changing one will change the other (see also the reference on Assignment statements).

Since mat[1:] is a list of lists, your best bet is probably to use copy.deepcopy() on assignment (see also the documentation of copy).

This post also contains some great explanations of the various copy methods.

Paul P
  • 3,346
  • 2
  • 12
  • 26