#319·wtfpython

Weird arithmetic with multiple `+` and `-`

Author: hillairetCreated Oct 2, 2023Updated Feb 24, 2025
Labelsnew snippets

Hello. Cool collection of WTFs I made a blog post about something that belongs in this collection.

I'd be happy to write up a section for it. Where should I put it? Any suggestion? Maybe right before or after the "Not knot" section that also deals with order precedence?

TL;DR This is all valid python:

python
>>> 1 +-+-+ 1
2
>>> 1 ++++++++++++++++++++ 1
2
>>> 1 ------- 1
0
>>> 1 ------ 1
2

It's all good an dandy until you use it with // and then things get weird:

python
>>> 2 + 5 // 2
4
>>> 2 -- 5 // 2
5

>>> 2 +-- 5 // 2
4
>>> 2 -+- 5 // 2
5
>>> 2 --+ 5 // 2
5

It's all explained by the operation precedence but it's very counter intuitive!