Skip to content
Quantoros

How do I copy an object in Python?

PythonLevel: Intermediate

How do I copy an object in Python?

Hints
  • Identify object types, mutability and execution order.
  • Trace a minimal example: which values and references change?

Answer

In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.

Some objects can be copied more easily. Dictionaries have a copy() method:

newdict = olddict.copy()

Sequences can be copied by slicing:

new_l = l[:]

Source and licence: Python 3.14.0 Programming FAQ — Python Software Foundation · PSF-2.0

Related questions