0

Today i am reading a book and found that list can be assign like x = list[:], but befor i read that i assign list like x=list But what is the difference ? Assume that lis = [1,2,34,5,1,243,34] is a list. Now i assign the lis to lis_a,lis_b and lis_c

>>> lis = [1,2,34,5,1,243,34]
>>> lis_a = lis
>>> lis_b = lis[:]
>>> lis_c = lis

when i print all those variables value then the output is same.

>>> print(lis,'\n',lis_a,'\n',lis_b,'\n',lis_c)
 [1, 2, 34, 5, 1, 243, 34] 
 [1, 2, 34, 5, 1, 243, 34] 
 [1, 2, 34, 5, 1, 243, 34] 
 [1, 2, 34, 5, 1, 243, 34]

But when i print the id of those variable then the values are same expect lis_b because i assign lis_b by lis[:]

print(id(lis),'\n',id(lis_a),'\n',id(lis_b),'\n',id(lis_c))
 45131136 
 45131136 
 45130016 <-- this is for lis_b
 45131136

Why this happend ? Is there any time complexity behind it ?

  • Feel free to reopen and rehammer; I don't mind. – TigerhawkT3 May 19 '16 at 20:07
  • 1
    `x = lst` copies the *reference*, `x = lst[:]` copies the list and assigns the reference of the new list. – poke May 19 '16 at 20:07
  • @vaultah yea, i am reading that.. – MD Sijad Faisal May 19 '16 at 20:08
  • 1
    See [What does \[:\] in Python mean](http://stackoverflow.com/q/6167238/2301450) and [What does \[:\] mean in python? \[duplicate\]](http://stackoverflow.com/q/14879933/2301450) – vaultah May 19 '16 at 20:10
  • @poke which take more time ? copies the reference or copies the list and assigns the refernce of new list ? – MD Sijad Faisal May 19 '16 at 20:10
  • 1
    @MDSijadFaisal References are just “pointers” to some object that lives in memory. Copying a reference just means having another of those pointers to the same object. That’s a very cheap operation but also means that both variables refer to the same object (so changing one list, changes the other one too since it’s the same list). – As for “copying a list”, this is more *cloning* the whole list, so it creates a completely new list object that contains the same values as the old one. Obviously that’s a more complicated process; but both have their use and you should think about what you *need*. – poke May 19 '16 at 20:15

0 Answers0