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
planets = ["Mercury", "Venus", "Earth"]
other_planets = planets
sorted_planets = sorted(planets)
planets[0] = "Jupiter"
print(planets)
print(other_planets)
print(sorted_planets)
Output:
['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.
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)
Output:
[['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]]