Python “don’t treat me like others”

achievement-adult-book-1181671

Hi, all its a long time I haven’t posted any article got little busy with all the professional stuff. in the meantime, I got interested towards Machine learning and AI, I think this is the right time I should start blogging as I am on the journey towards machine learning I was going through python most popular language to drive AI space and got an interesting topic that I should share with all python beginners.

two topics that I’ll cover today:

  1. what is a Shallow copy in python
  2. Argument passing to function in python is always passed by reference

What is a Shallow copy in python

In python whenever we copy a mutable object to other objects using assignment operator or inbuilt function ( = ), .copy()  or [:]  it a shallow copy i.e the object reference is tagged to the new object So any change made to the new object is reflected back to the old object.

Argument passing to function in python:

All folks how have taken tech subject in their academics had studied one important programming topic “pass by value and pass by reference” while passing an argument to functions. In python, it is to be remembered that all arguments passed to a function are passed by reference and this is also due to the shallow copy effect of python. study the below codes to grasp the above-discussed topic

a = [[1,2],[3,4],[5,6],[7,8]]
b = [1,2,3,4,5,6,7,8]
def change(y):
    x = y
    if isinstance(x[0], list):
        x[0][1] = 'change'

    if isinstance(x[0], int):
        x[0] = 'change'

change(a)
print(a)

change(b)
print(b)

# output

# a: [[1, 'change'], [3, 4], [5, 6], [7, 8]]
# b: ['change', 2, 3, 4, 5, 6, 7, 8]
Lets change the code to get rid of default pass by reffrence effect
a = [[1,2],[3,4],[5,6],[7,8]]
b = [1,2,3,4,5,6,7,8]
def change(y):
    x = y.copy() # y[:] or list(y) has same effect
    if isinstance(x[0], list):
        x[0][1] = 'change'

    if isinstance(x[0], int):
        x[0] = 'change'

change(a)
print(a)

change(b)
print(b)

# output

# a: [[1, 'change'], [3, 4], [5, 6], [7, 8]]
# b: [1, 2, 3, 4, 5, 6, 7, 8]

see the pass by reffrence effect removed form object b but it is still working
on object a, because

x[0] element for object “b”  is an immutable type (int) but for x[0] element for object “a” is a mutable type (list), So Shallow copy effect is still working.

Now comes the question of who will rescue us to overcome this situation well python’s copy module is there to help us to achieve deep copy

check below code :

import copy
a = [[1,2],[3,4],[5,6],[7,8]]
b = [1,2,3,4,5,6,7,8]
def change(y):
    x = copy.deepcopy(y)
    if isinstance(x[0], list):
        x[0][1] = 'change'

    if isinstance(x[0], int):
        x[0] = 'change'

change(a)
print("a: ",a)

change(b)
print("b: ",b)

# output

# a:  [[1, 2], [3, 4], [5, 6], [7, 8]]
# b:  [1, 2, 3, 4, 5, 6, 7, 8]


Protected by Copyscape