1
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?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
krkart
  • 435
  • 4
  • 11

2 Answers2

5

== 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.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
2

list() creates a new list. The newly created list equal (==) to the original but not identical (is).

heemayl
  • 39,294
  • 7
  • 70
  • 76
Mike Müller
  • 82,630
  • 20
  • 166
  • 161