Aliasing and Cloning of List objects in Python

#list #objects ##cloning ##aliasing

Abhijit Barik Mar 23 2021 · 1 min read
Share this

The process of giving another reference variable to the existing list is called aliasing.

Example:-

1) x=[10,20,30,40]

2) y=x

3) print(id(x))

4) print(id(y))

                                                                   graphical representation of  aliasing

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.

  • Example:-
  • 1) x=[10,20,30,40]

    2) y=x

    3) y[1]=777

    4) print(x)  # ==>[10,777,30,40]

                                                                       graphical representation of above code

    To overcome this problem we should go for 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:

    1) x=[10,20,30,40]

    2) y=x[:]

    3) y[1]=777

    4) print(x) # ==>[10,20,30,40]

    5) print(y) # ==>[10,777,30,40]

                                                                       graphical representation of above code

    2. By using copy() function:

    1) x=[10,20,30,40]

    2) y=x.copy()

    3) y[1]=777

    4) print(x) # ==>[10,20,30,40]

    5) print(y) # ==>[10,777,30,40]

                                                     graphical representation of above code

    Q. Difference between = operator and copy() function

  • = operator meant for aliasing
  • copy() function meant for cloning
  • Comments
    Read next