Answers for "python deep copy"

4

python clone object

import copy

new_ob = copy.deepcopy(old_ob)
Posted by: Guest on December-29-2020
5

example of a deep copy in python

# deep copy example in python
import copy

old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)

old_list[1][0] = 'BB'

print("Old list:", old_list)
print("New list:", new_list)

# OUTPUT
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
Posted by: Guest on September-20-2020
0

Python Deep Copy

import copy

l1 = [1,3,[9,4],6,8]
l2 = copy.copy(l1) #Making a shallow copy

print('List 1 = ', l1)
print('List 2 = ', l2)

print('Performing change in list 2')
l2[2][0] = 5

print('List 1 = ',l1)
print('List 2 = ',l2)
Posted by: Guest on July-10-2021
0

python deep copy

# explaining why we need deepcopy
x = [0,1]
y = x
x.append(2)
print(x)
print(y)
# result: [0, 1, 2]
# result: [0, 1, 2]

import copy

some_list = [[0, 0, 0], [1, 1, 1], [2, 2, 2]]
other_list = copy.copy(some_list)
some_list.append([3, 3, 3])
print(some_list)
print(other_list)
# result: [0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]
# result: [0, 0, 0], [1, 1, 1], [2, 2, 2]]

del some_list[2]
some_list[1][0] = 'One'
print(some_list)
print(other_list)
# result: [0, 0, 0], ['One', 1, 1], [2, 2, 2]]
# result: [0, 0, 0], ['One', 1, 1], [2, 2, 2]]

#this problem doesn't happen with copy.deepcopy()
Posted by: Guest on April-08-2021
0

Python Deep Copy

import copy

l1=[1,3,[9,4],6,8]
l2=copy.deepcopy(l1) #Making a deep copy

print('List 1 = ', l1)
print('List 2 = ', l2)

print('Performing change in list 2')
l2[2][0] = 5

print('List 1 = ',l1)
print('List 2 = ',l2)
Posted by: Guest on July-10-2021

Python Answers by Framework

Browse Popular Code Answers by Language