All posts
Tech Insights

Python Can Be Weird – Let's Look at Some Peculiar Examples

Sometimes Python behaves in ways that make you do a double-take. Here are four classic curiosities – and why they are actually perfectly logical.

Stefan HedenströmAuthorStefan Hedenström·
Python Can Be Weird – Let's Look at Some Peculiar Examples

Python is a fantastic language, but sometimes it behaves in ways that make you do a double-take. Here are four classics – and the explanation behind them.

Example 1 – 8-bit problem?

Python
>>> a = 256>>> b = 256>>> a is bTrue>>> a = 257>>> b = 257>>> a is bFalse

CPython caches small integers from -5 to 256 as singletons. The same object is reused everywhere. Outside this range, new objects are created every time.

Example 2 – where did Ruby go?

Python
>>> programming = dict()>>> programming[5.5] = "JavaScript">>> programming[5.0] = "Ruby">>> programming[5] = "Python">>> programming[5.0]'Python'

5 == 5.0 is true, and both hash to the same value. Therefore, programming[5] = "Python" overwrites programming[5.0]. Ruby disappeared.

Example 3 – invalid syntax?

Python
>>> not x == yTrue>>> y == not xSyntaxError: invalid syntax

not is a unary operator with lower precedence than ==. not x == y is interpreted as not (x == y). But y == not x becomes syntactically incorrect – the parser expects an expression after ==, not an operator.

Example 4 – huh?

Python
>>> a = "wtf"; b = "wtf"; a is bTrue>>> a = "wtf!"; b = "wtf!"; a is bFalse

CPython interns short strings that look like identifiers. "wtf" becomes the same object. "wtf!" contains ! and is not considered an identifier – no interning, two different objects.

Conclusion

Python is full of such "gotchas" – and they are usually perfectly logical once you understand what's happening under the hood. Always use == for value comparison and is only when you truly mean the same object in memory.

Share
SHEBANG – hashtag och utropstecken
LinkedIn X
Talk to us
Ronnie Qvist
Ronnie Qvist
Sales & customer relations · SHEBANG
Usually replies within a few hours

Write a few lines or call directly, I'll connect you with the right specialist on the team. No pipeline nonsense, no pitch.

Reply same day
Right person, directly
No pitch
Talk to us

Did this post raise a question?

Write a few lines about your situation, and we'll come back with the right person on the team, usually the same day.

We usually reply the same day. Never spam.