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
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