Sunday 24 May 2020

List Data type- Part-3


 

Aliasing and Cloning of List objects:

Aliasing
The process of giving another reference variable to the existing list is called aliasing.
Eg:
x=[10,20,30,40]
y=x
print(id(x))
print(id(y))

 The problem in this approach is by using one reference variable if we are changing content, then those changes will be reflected to the other reference variable.
x=[10,20,30,40]
y=x
y[1]=777
print(x) ---------->[10,777,30,40]





To overcome this problem we should go for cloning.
Cloning :
The process of creating exactly duplicate independent object is called cloning.
We can implement cloning by using
  •  slice operator
  • or by using copy() function

1. By using slice operator:
x=[10,20,30,40]
y=x[:]
y[1]=777
print(x) ------>[10,20,30,40]
print(y) ------->[10,777,30,40]


2. By using copy() function:
x=[10,20,30,40]
y=x.copy()
y[1]=777
print(x) ----->[10,20,30,40]
print(y) ------>[10,777,30,40]


Difference between = operator and copy() function
= operator is meant for aliasing
copy() function is meant for cloning

No comments:

Post a Comment