Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python copy a list and edit this copy

Im trying to copy a list and then change something in that copy, but it always changes in both lists.

_team1_picks = team1_picks.copy()
_team2_picks = team2_picks.copy()
for karte in _team1_picks:
    print(team1_picks, _team1_picks)
    karte[2],karte[3] = karte[3],karte[2]
    print(team1_picks, _team1_picks)
for karte in _team2_picks:
    print(team2_picks, _team2_picks)
    karte[2],karte[3] = karte[3],karte[2]
    print(team1_picks, _team1_picks)

This is my code and the output is:

[['Kafe', 1, 7, 3]] [['Kafe', 1, 7, 3]]
[['Kafe', 1, 3, 7]] [['Kafe', 1, 3, 7]]
[['Oregon', 1, 7, 5]] [['Oregon', 1, 7, 5]]
[['Oregon', 1, 5, 7]] [['Oregon', 1, 5, 7]]

I also tried to slice the lists with

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

_team1_picks = team1_picks[:]
_team2_picks = team2_picks[:]

but with the same result.

On another occasion it works with .copy():

_decider = decider.copy()
_decider[1],_decider[2] = decider[2],decider[1]

Here only the _decider list is getting modified.
Now im confused why it works one time but not the othert time, and how to solve this issue.

>Solution :

All of the things you’re doing are just copying the top-level list. This is known as a shallow copy. If you want to recursively copy all lists, including nested sublists, you can use a deep copy:

new_list = copy.deepcopy(old_list)

This will recursively copy all lists and sublists.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading