-1

in a Python program, I need to define a list from another one, and the delete an element from the new list, it also removes it from the other list. does anyone know how to counter that ?

below, an example :

source = [4, 5, 6]
new = source
new.remove(5)
print(new) # output [4, 6] has wanted
print(source) # output [4, 6] but wanted [4, 5, 6]

3 Answers3

0

use copy():

source = [4, 5, 6]
new = source.copy()
new.remove(5)
print(new) #output: [4, 6]
print(source) #output: [4, 5, 6]
Tal Folkman
  • 2,368
  • 1
  • 7
  • 21
0

When you use new = source both variables point to the same place in your storage. What you need to use is:

source = [4, 5, 6]
new = source.copy()
new.remove(5)
print(new) # output [4, 6] has wanted
print(source) # output [4,5, 6] but wanted [4, 5, 6]

This will copy the elements inside the source and assign it to the new variable.

If your list contains mutable things such as objects, you should use a deep copy.

from copy import deepcopy
new = deepcopy(source)
0

You can use .copy() because when you use new=source the entry point will be same. So if you delete one item from one list it will delete it from both.

Code:

source = [4, 5, 6]
new = source.copy()
new.remove(5)
print(new)
print(source)

Output:

[4, 6]
[4, 5, 6]