-->

Python Object reference well explained with list

Assume you have a list and you want to make exact copy of the list.

What command you will use in python to copy a list from another list.

I used List1=List2 and List1 got copied as exactly as List2 but what happen internally is they have shared command object reference location.

Dont believe ? then lets try and try to see both lists location with id function id()

I mean do as  id(List1) and id(List2) , you will find command location for these two which means they are sharing common location and what ever operations you do they will reflect on both lists.And this is completely harmful and dangerous.

So to avoid this list copying can be done in other methods where two list will have two different object locations.

They are

list2=copy.copy(list1)
(or)
list2=list1[:]
(or)
list2=list(list1)

and for more information about object reference understanding in python I recommend you to read these

http://stackoverflow.com/questions/36244451/how-to-program-python-variable-to-point-different-reference-location-but-same-va/36244490#36244490

http://www.python-course.eu/python3_variables.php


Share on Google Plus

About RAJA SEKHAR REDDY GENUPULA

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.