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 :: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. 
Python :: filter dictionary python 
Python :: cannot unpack non-iterable int object when using python dicitonary 
Python :: how to refresh page in flask 
Python :: what are arrays in python 
Python :: random.choices without repetition 
Python :: creating an object in python 
Python :: matplotlib subplots share x axis 
Python :: arithmetic operators in python 
Python :: del en python 
Python :: pygame draw square 
Python :: fill na with average pandas 
Python :: opencv python rgb to hsv 
Python :: python elif 
Python :: tkinter filedialog 
Python :: partition python 
Python :: how to add one to the index of a list 
Python :: swap case python 
Python :: django-chartjs 
Python :: python multiclass inheritance with inputs 
Python :: python port forwarding 
Python :: put grid behind matplotlib 
Python :: pandas dataframe apply function with multiple arguments 
Python :: python random distribution 
Python :: how to find the shortest word in a list python 
Python :: python numpy euler 
Python :: one line try except python 
Python :: how to use visualize_runtimes 
Python :: pyevtk documentation writearraystovtk 
Python :: how to add twoo segmen time series in a single plot 
ADD CONTENT
Topic
Content
Source link
Name
2+3 =