I am a beginner in Python, I cannot understand assignment operator clearly, for example:
list1 = [\"Tom\", \"Sam\", \"Jim\"]
list2 = list1
In your example the identifiers list1
and list2
are references to the same underlying object (just different names for the same thing).
id()
can be used to see if the same underlying object is being referenced.
>>> list1 = ["Tom", "Sam", "Jim"]
>>> list2 = list1
>>> id(list1)
44259368
>>> id(list2)
44259368
To create a copy of the defined list use the [:]
notation, or deepcopy
as Matthew has mentioned. You'll notice that when this is done the location/id has changed.
>>> list3 = list1[:]
>>> id(list3)
44280208
About the id command:
>>> help(id)
Help on built-in function id in module __builtin__:
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)