Monday, March 30, 2020

shallow copy in python


l1=[10,20,30,40]
l2=l1
l2[2]=70
print("l2:",l2)
print("l1:",l1)

output:
l2: [10, 20, 70, 40]
l1: [10, 20, 70, 40]

example 2:

l1=[10,20,30,40]
l2=l1.copy()

l2[2]=70
print("l2:",l2)
print("l1:",l1)

output:
l2: [10, 20, 70, 40]
l1: [10, 20, 30, 40]

example 3:

import copy

l1=[10,20,[30,40],50]
#l2=l1.copy()
#it dnot work for list inside another list
l2=copy.copy(l1)

l2[2][0]=70
print("l2:",l2)
print("l1:",l1)

output:
l2: [10, 20, [70, 40], 50]
l1: [10, 20, [70, 40], 50]

No comments:

Post a Comment

python class topic video