Member-only story
5 Times Python Made Me Say WTF
Learn some funny Python oddities

Python is a popular programming language. As with any other great programming language, Python sometimes makes the developers scratch their heads.
Today I will show you five “funny” WTFs in Python. And no, I’m not talking about bugs.
1. Sometimes Two Equal Numbers Aren’t Equal
Let’s use Python’s is
operator to compare two equal numbers and see what happens:
>>> a = 256
>>> b = 256
>>> a is b
True>>> a = 257
>>> b = 257
>>> a is b
False
How does it work
First of all, the ==
operator is used to check if two variables are equal. The is
operator, on the other hand, checks if the variables point to the same object.
Secondly, Python does some optimization under the hood. Some commonly used objects, e.g., small numbers (between -5 and 256) are allocated only once. But larger numbers are allocated on-demand as many times as needed.
Here’s an example:
>>> x = 1000
>>> y = 1000
>>> z = 1000
The number 1000
is allocated three times, so even though the numbers x
,y
, and z
are equal, they all have a different 1000
assigned to them. However, here is another example:
>>> a = 255
>>> b = 255
>>> c = 255
The number 255 has been allocated only once, so the “same 255
” is used three times. And this is actually what the is
operator is interested in, rather than the values being equal.

The key takeaway: Don’t use is
to compare numbers, even though it sometimes works.
2. It Is What It Isn’t
>>> 'something' is not None
True
>>> 'something' is (not None)
False
How does it work
is not
is actually a single binary operator. Thus, it has behavior different than usingis
andnot
separately.is not
returnsFalse
if the compared variables…