python object id

python returns unique integer for any object. this is constant and unique during the lifetime of the object.


>>> x=10
>>> id(x)
7966548
>>> 

two objects can have same id. while copying one list to another

>>> list1=[1,2,3,4,5]
>>> id(list1)
40917912
>>> list2=list1
>>> id(list2)
40917912

to get different id’s use the following method

>>> list3=list1[:]

>>> id(list3)
40960728

>>> list1
[1, 2, 3, 4, 5]
>>> list2
[1, 2, 3, 4, 5]
>>> list3
[1, 2, 3, 4, 5]
>>> list2[2]=23
>>> list2
[1, 2, 23, 4, 5]
>>> list1
[1, 2, 23, 4, 5]
>>> list3
[1, 2, 3, 4, 5]

Any modification to list2 affects the list1 and vice versa. But any changes to list3 will not affect list1.

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