Sorted and change - shallow copy
- Sorted creates a shallow copy of the original list
- If the list elements are simple values that creates a copy
examples/lists/sorted_and_change.py
planets = ["Mercury", "Venus", "Earth"] other_planets = planets sorted_planets = sorted(planets) planets[0] = "Jupiter" print(planets) print(other_planets) print(sorted_planets)
['Jupiter', 'Venus', 'Earth'] ['Jupiter', 'Venus', 'Earth'] ['Earth', 'Mercury', 'Venus']
- If some of the elements are complex structures (list, dictionaries, etc.) then the internal structures are not copied.
- One can use copy.deepcopy to make sure the whole structure is separated, if that's needed.
examples/lists/sorted_and_change_deep.py
planets = [ ["Mercury", 1], ["Venus", 2], ["Earth", 3], ["Earth", 2] ] other_planets = planets sorted_planets = sorted(planets) print(sorted_planets) planets[0][1] = 100 print(planets) print(other_planets) print(sorted_planets)
[['Earth', 2], ['Earth', 3], ['Mercury', 1], ['Venus', 2]] [['Mercury', 100], ['Venus', 2], ['Earth', 3], ['Earth', 2]] [['Mercury', 100], ['Venus', 2], ['Earth', 3], ['Earth', 2]] [['Earth', 2], ['Earth', 3], ['Mercury', 100], ['Venus', 2]]