Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Shallow copy in python

import copy
list1 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
list2 = copy.copy(list1)
print("Old list:", list1)
print("New list:", list2)
Comment

shallow copy deep copy python

#shallow copy: one level deep, only references of nested child objects
#deep copy: full independent copy

# shallow copy: only 1 level deep (i.e. not work on nested list)
import copy

org = [0, 1, 2, 3]
# 4 options
cpy = copy.copy(org)    #use copy module
cpy = org.copy()        #list has a copy option
cpy = list(org)         #make new list
cpy = org[:]              #slicing trick

cpy[0] = 100
print(org)
print(cpy)
# [0, 1, 2, 3]
# [100, 1, 2, 3]


#deep copy: 
import copy

org = [[0, 1, 2, 3], [4, 5, 6, 7]]
cpy = copy.deepcopy(org)
cpy[0][1] = 100
print(org)
print(cpy) 
# [[0, 1, 2, 3], [4, 5, 6, 7]]
# [[0, 100, 2, 3], [4, 5, 6, 7]]


# level of copy layers also apply to custome classes
import copy

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Company:
    def __init__(self, boss, emp):
        self.boss = boss
        self.emp = emp

p1 = Person('Alex', 55)
p2 = Person('Joe', 25)
company = Company(p1, 2)
company_clone = copy.deepcopy(company)  #deepcopy bc class is 2 layers deep
company_clone.boss.age = 56
print(company_clone.boss.age)
print(company.boss.age)
# 56
# 55
Comment

PREVIOUS NEXT
Code Example
Python :: python format strings 
Python :: sort by the frequency of occurrences in Python 
Python :: Reverse an string Using Stack in Python 
Python :: Python Tkinter RadioButton Widget 
Python :: convert string to float python 
Python :: python try else 
Python :: installing required libraries in conda environment 
Python :: input two numbers in python in a single line 
Python :: valid parentheses 
Python :: Python not readable file 
Python :: how to make a random int in python 
Python :: len python 
Python :: tkinter include svg in script 
Python :: python check for alphanumeric characters 
Python :: cv2.imwrite 
Python :: Splitting strings in Python without split() 
Python :: replace string between two regex python 
Python :: django admin.py 
Python :: how to install python library 
Python :: skimage local threshold 
Python :: make a post request in python 
Python :: print example in python 
Python :: sns boxplot 
Python :: python socket get client ip 
Python :: lable on graph in matplotlib 
Python :: TypeError: ‘float’ object is not callable 
Python :: numpy array divide each row by its sum 
Python :: django create view 
Python :: for each loop python 
Python :: how to find a prime number 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =