To increment a counter in Python, you can use the += increment operator and add a number to the counter.

i = 0
i += 1

print(i)

#Output:
1

The increment operator is the equivalent of adding a number via simple addition.

i = 0
i = i + 1

print(i)

#Output:
1

In Python, counters are frequently used when iterating over an object or keeping track of a count for later use.

There are many useful operators in Python and one such operator which makes counting easy is the increment operator +=.

You can use the += to add a number to another number and increment a counter.

For example, if you want to add one to a number and increment a counter, you can do so with the following Python code.

i = 0
i += 1

print(i)

#Output:
1

This is the equivalent as using simple addition to add to a number.

i = 0
i = i + 1

print(i)

#Output:
1

You can add any number with the increment operator including floats.

i = 0
i += 2

print(i)

i += 2.0

print(i)

#Output:
2
4.0

Decrement Counter in Python with Decrement Operator -=

If you want to go the other way and decrement a counter, then you can use the Python decrement operator -=.

The decrement operator works the same as the increment operator.

Below shows you a simple example of how you can decrement a counter in Python with the decrement operator.

i = 0
i -= 1

print(i)

#Output:
-1

Hopefully this article has been useful for you to learn how to use the increment operator and how to increment a counter in Python.

Categorized in:

Python,

Last Update: February 26, 2024