Shallow Copy in Python

When you say something-else = something in Python creates a shallow copy of that something. This might be new for someone migrating from a C/C++ background and it might take a newbie a long time to realize ( sometimes after a lot of hairloss ).

When you write y=x, y will now point to the location of the object x was pointing to.This can be shown with the help of the id() built-in function

>>> a = [0,1]
>>> b = a
>>> b[0] = 1
>>> print b
[1, 1]
>>> print a
[1, 1]
>>> print id(a),id(b)
44504048 44504048

This might always be that apparent, observe the following code

The reason is, Integers unlike Lists are immutable.When we try to change the value of y , a new integer object is created and assigned to y, since changing its value isn’t possible.

>>> x = 100
>>> y = x
>>> print id(x),id(y)
31959540 31959540
>>> y = 200
>>> print y
200
>>> print x
100
>>> print id(x),id(y)
31959540 31960324

Leave comments for any further clarification or to point out errors .

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s