Search code examples
pythonlistcopy

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

_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.