Search notes:

Python: copying objects

The assignment operator does not create a new object, it merly makes the variable on its left side reference the object that is referenced by the expression on its right side.
This page tries to show some tecniques how objects can be copied.

Copying a sequence

A sequence can be copied by slicing it:
orig    = [1,2,3]

aliased = orig
copied  = orig[:]

orig.append(4)

print('elements in aliased:')
for x in aliased:
    print('  {}'.format(x))
#
# elements in aliased:
#   1
#   2
#   3
#   4

print('elements in copied:')
for x in copied:
    print('  {}'.format(x))
#
# elements in copied:
#   1
#   2
#   3
Github repository about-Python, path: /objects/copy/sequence.py

Copying a dictionary

A dict has the .copy() method:
orig    = [1,2,3]

aliased = orig
copied  = orig[:]

orig.append(4)

print('elements in aliased:')
for x in aliased:
    print('  {}'.format(x))
#
# elements in aliased:
#   1
#   2
#   3
#   4

print('elements in copied:')
for x in copied:
    print('  {}'.format(x))
#
# elements in copied:
#   1
#   2
#   3
Github repository about-Python, path: /objects/copy/sequence.py

Index