3
even = [10, 4, 6, 8]
another_even = list(even)
print(another_even is even)
if another_even == even:
    another_even.sort( reverse=True )
    print(even)
else:
    print("Yay")

Output: False

[10, 4, 6, 8]

Even though I have created two seperate list then why the if condition is true.

berto
  • 8,215
  • 4
  • 25
  • 21
  • 3
    Possible duplicate of [Is there a difference between \`==\` and \`is\` in Python?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python) – Abdul Niyas P M Jan 20 '18 at 14:23
  • The if condition is True because the two objects are equal but they are not the same object. They are two diffferent containers with the same numbers inside. list(data) creates a new list from the data in data. data can be any iterable. In this case there is the coincidence of data being also a list. – joaquin Jan 20 '18 at 14:44

1 Answers1

2
even = [10, 4, 6, 8]
another_even = list(even)

even is one list another_even is a different list which you constructed by using the elements in even.

Notice: different. They are two different objects.

That's why:

print(another_even is even)

prints False. It is because even and another_even are not the same object.

If you had done this:

another_even = even

you would have gotten True

But now you test for equality with:

if another_even == even:
    another_even.sort( reverse=True )
    print(even)
else:
    print("Yay")

And == will compare the elements inside even against the elements inside another_even. Because the length of the lists and the elements are equal, the comparison evaluates to True and this code executes:

    another_even.sort( reverse=True )
    print(even)

You could think of the == comparison as executing this other code:

result = True
for x, y in zip(even, another_even):
    if x != y:
        result = False
        break

The elements are compared one to one and in case one pair fails to be equal, the result will be False. In your case all elements are equal.

Note: you can check that the objects even and another_even are different doing this:

print(id(even))
print(id(another_even))

And the output will be different, hence the False from even is another_even

mementum
  • 3,153
  • 13
  • 20