copy
Copying objects: the shallow copy() shares nested objects with the original, and the deep deepcopy() copies everything.
- Returns
- A new object: a shallow or deep copy of the original.
Example
#import copy
team = {"name": "Reds", "members": ["Emma", "Jack"]}
alias = team
shallow = copy.copy(team)
deep = copy.deepcopy(team)
team["members"].append("Mia")
team["name"] = "Red Dragons"
print(alias["name"], alias["members"])
print(shallow["name"], shallow["members"])
print(deep["name"], deep["members"])alias is the same dictionary, so it sees both changes. The shallow copy has its own team name, but the same list of members. The deep copy did not change at all.
Definition and usage
#The assignment b = a does not copy data, it only creates a second name for the same object, so a change to a list through b is also visible through a. The copy module provides two functions for making real copies: copy.copy() (a shallow copy) and copy.deepcopy() (a deep copy).
A shallow copy creates a new outer object, but its items point to the same objects as in the original. For a list of numbers or strings, that is enough. For a list of lists or a dictionary containing lists, changing a nested list in the copy also changes the original. A shallow copy is also made by list.copy(), dict.copy(), list(list_), and the slice list_[:].
A deep copy recursively copies all the nested objects, so the result is completely independent of the original. It is slower, but safe for complex structures, e.g. a game state or a configuration you want to change without touching the template. Both functions also handle objects of your own classes. Since Python 3.13, there is also the copy.replace() function, which creates a copy with changed fields, e.g. of a @dataclass object.
Syntax
#import copy
copy.copy(obj)
copy.deepcopy(obj)Parameters
#obj
any object
The object to copy: a list, dictionary, set, or an object of your own class.
More examples
#import copy
board = [[0, 0], [0, 0]]
shallow = board.copy()
deep = copy.deepcopy(board)
shallow[0][0] = 1
deep[1][1] = 9
print(board)
print(shallow)
print(deep)
print(board[0] is shallow[0], board[0] is deep[0])import copy
class Character:
def __init__(self, name, inventory):
self.name = name
self.inventory = inventory
hero = Character("Emma", ["sword", "map"])
clone = copy.deepcopy(hero)
clone.name = "Emma's clone"
clone.inventory.append("shield")
print(hero.name, hero.inventory)
print(clone.name, clone.inventory)Good practices
#- If the structure contains only numbers, strings, and tuples of such values, a shallow copy is enough. Use
deepcopy()for nested lists, dictionaries, and objects. - The notation
[[0] * 3] * 3creates three references to one list. Build a board with the expression[[0] * 3 for _ in range(3)]. - You can check whether two names point to the same object with the
isoperator.
Related entries
#- list.copy()Returns a shallow copy of a list.
- list()Creates a list, either empty or from the items of another iterable.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
- List slicing [start:stop:step]Getting, replacing, and deleting fragments of a list by index.
- dict.update()Adds pairs from another dictionary or from arguments to a dictionary, overwriting existing keys.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.