num = [1,2,3,4]
num == list(num)
It gives True, where as,
num is list(num)
gives False.
What is the difference between these two? What python does in both statements?
num = [1,2,3,4]
num == list(num)
It gives True, where as,
num is list(num)
gives False.
What is the difference between these two? What python does in both statements?
==
calls list.__eq__
for the two lists, which compares the contents. is
compares the object references. is
returning True
means that both names point to the same object in memory.
What the result tells you is that list
always makes a shallow copy, even if the input is another list. The reason is that list
is a mutable type. You want to be able to modify one list without modifying the other, otherwise why bother calling the constructor at all?
The same behavior does not happen with tuple
, which is immutable. tuple(some_tuple) is some_tuple
will be True
.
list()
creates a new list. The newly created list equal (==
) to the original but not identical (is
).