Home > Net >  How to prevent two lists in python from synching in python?
How to prevent two lists in python from synching in python?

Time:09-13

I have narrowed down the problem this much. I have a list [1, 3, 2, 1] and I am looking to store that list in a variable, remove one item index 2 and store the result in another variable. This is the code:

sequence = [1, 3, 2, 1]

temporary_list = sequence

del temporary_list[2]

print(sequence)
print(temporary_list)

However both sequence and temporary_list print the same values ([1, 3, 1]). What am I doing wrong? What would be the right way to get [1, 3, 2, 1] and [1, 3, 1]?

CodePudding user response:

Python 2.x: temporary_list = sequence[:]

If python 3.x:

Temporary_list = sequency.copy()

Python assigned objects are just a binding between a target and a object, if you want a new object you must "copy" it to create a new object. Look at the official docs for more info:https://docs.python.org/3/library/copy.html

  • Related