+ 1

What is the " is " condition?

When there is a line like " if a is b: statments "

8th Sep 2019, 6:28 PM
Gwlanbzh
Gwlanbzh - avatar
5 Answers
+ 5
This item has been asked frequently, but here a short definition: "==" is for value equality. Use it when you would like to know if two objects have the same value. "is" is for reference equality. Use it when you would like to know if two references refer to the same object.
8th Sep 2019, 7:00 PM
Lothar
Lothar - avatar
+ 4
The rules of the language specify that mutable objects like lists *have to* be separate entities. a = [] b = [] a.append(42) Now if Python secretly just had one list for a and b (initially they look the same), the user could not rely on having two lists and fill them separately. For immutable objects, on the other hand, a Python implementation is allowed to either store just one element, or two, or sometimes this and sometimes that. Because it doesn't matter from the point of the user - you can't change them anyway, so nothing bad can happen. Normally you would not feel the need to use 'is' with immutables, but with lists for example it can help you to keep things separate. I remember a funny case though: stuff = ['hello', False, 5.7, 0] print(*[x for x in stuff if x != 0]) If you do this, False will not be printed, because it evaluates to 0. You have to write: print(*[x for x in stuff if x is not 0]) Now every thing but real zeros gets printed out. Looks this 0 *has to* be a singular!
9th Sep 2019, 8:12 AM
HonFu
HonFu - avatar
+ 3
Using is can be confusing when you test it with lists or other iterables (except strings). When: 0 is 0 -> True 5 is 5 -> True But: [1, 2, 3] is [1, 2, 3] -> False Even worse: "589" is "589" -> True (1, 4) is (1, 4) -> False I can not really explain why ids of strings don't behave like ids of other iterables. But I think Python has a cool way to store "primitive datatypes". When you store a "primitive" value: a = 6 6 will be created and stored somewhere, when you do: b = 6 It does not create 6 again, but it uses the same 6, which was already stored. When you do: a += 2 It does not change the stored value of 6, but it will create and store a new value 8 (6+2 = 8). When there is no variables referring to the integer 6, it will finally be removed from the store. This can not work similarly for iterables.
9th Sep 2019, 7:30 AM
Seb TheS
Seb TheS - avatar
+ 2
Every object in Python have an unique id. You can get that id using id function. Testing (a is b) equals (id(a) == id(b)).
8th Sep 2019, 7:58 PM
Seb TheS
Seb TheS - avatar
+ 1
Okay got it thanks everyone!
9th Sep 2019, 12:07 PM
Gwlanbzh
Gwlanbzh - avatar