Explain Codes LogoExplain Codes Logo

Behaviour of increment and decrement operators in Python

python
increment
assignment-expressions
best-practices
Nikita BarsukovbyNikita Barsukov·Sep 19, 2024
TLDR

In Python, increment and decrement operations are achieved with += 1 and -= 1. The ++ and -- syntax from languages like C is not supported:

counter = 1 counter += 1 # Increment all the way to... 2! counter -= 1 # Decrement back to square one. Or is it square 1?

Although ++ or -- won't raise syntax errors in Python, they aren't actually doing anything. They're just there, pretending to be useful. Sneaky, right?

The '+' operator: An imposter!

In Python, the + operator is nothing more than an identity operator. Let's say you have:

count = 1 ++count # No error, but also no effect. It's a lazy operator!

That's because Python interprets ++count as +(+count) which is essentially the same as count. So, the '+` operator snuck inside, disguising as '++'!

What about integers?

Integers in Python are immutable, behaving like an unchangeable trophee in a display case. When an integer is incremented, it's not that the trophee is getting bigger. Instead, you're giving a new trophee to the display case:

a = 1 # Look, a shiny trophy! a += 1 # Nope, this is a new one. The old one? Forget about it.

Assignment expressions: No, it's not homework

From Python 3.8 onward, we've been bestowed with assignment expressions using the := operator. That lets you inject some pre-increment vibes into expressions:

a = 1 while (a := a + 1) < 10: # The loop that keeps on giving... until 'a' is 10

Post-increment behavior is a tougher nut to crack, but we've got hammers:

a = 1 print((a := a + 1) - 1) # Prints 1, but 'a' now whispers 'I'm 2 now'

Custom behavior with pos

If you want to pull some tricks and give special meaning to the ++ syntax in your own class, you could rig the __pos__ method. Remember though, it's not increment-addict, it's just pretending:

class MyClass: def __pos__(self): # Disguise mode activated my_instance = MyClass() ++my_instance # Calls my_instance.__pos__() and asks 'Who are you, really?'

The art of readable increments

Python, being the Zen master, pushes for clarity and readability. Keep increments explicitly clear in a separate line.

a = 1 # Solving world hunger here a += 1 # You know what they say, 'Brevity is... wit'. Or was it 'it'?🤔

In the world of for-loops, let enumerate() handle your counting woes. No manual labor required!

for index, value in enumerate(iterable): # Let index take the burden of counting

In the realm of comprehensions, the count increments behind the scenes. Magic!

Beware of the pitfalls

Remember, Python is not C, Java or JavaScript. The increment and decrement work differently here.

  • Don't use ++ or -- expecting to change values; they are undercover no-ops.
  • Each time an integer is incremented or decremented, remember there's a new object backstage.