Coding

Python Increment by 1: Why There Is No ++ and What to Use

To increment a number by 1 in Python, write x += 1. Python has no ++ or -- operator, so x++ is a syntax error.

count = 0
count += 1
print(count)

Example output:

1

How += works

+= is an augmented assignment. It adds the right-hand side to the current value and stores the result back in the same target. The Python reference says x += 1 can be rewritten as x = x + 1 "to achieve a similar, but not exactly equal effect". Two differences are listed: in the augmented form x is evaluated only once, and when possible the operation is done in place, so the old object is modified instead of a new one being created.

For numbers, in-place makes no visible difference. Integers are immutable, so count += 1 always builds a new integer and rebinds the name. The distinction shows up with lists, covered below.

The same form exists for the other binary operators. The reference lists +=, -=, *=, @=, /=, //=, %=, **=, >>=, <<=, &=, ^= and |=. To change by a different amount, put that amount on the right:

x = 10
x += 5     # 15
x -= 1     # 14, this is how you decrement
x *= 2     # 28

What happens if you type x++

Python's grammar has no postfix increment, so the interpreter rejects it before running anything. Example output (the exact wording of the message varies between Python versions):

>>> x = 1
>>> x++
  File "<stdin>", line 1
    x++
       ^
SyntaxError: invalid syntax

The prefix form is stranger, because it does not fail. ++x parses without error:

>>> x = 1
>>> ++x
1
>>> x
1

The reference explains why: the unary + operator "yields its numeric argument unchanged". So ++x is +(+x), two no-op operations, and x keeps its value. The same applies to --x, which is -(-x) and gives back the original number, not a decremented one. If you port code from C, Java or JavaScript and the counter never moves, look for ++x or --x first.

Increment a counter in a loop

A manual counter is the usual place people reach for ++:

total = 0
for price in [4, 8, 15]:
    total += price
print(total)

Example output:

27

A while loop needs the increment written out, and forgetting it gives an infinite loop:

attempt = 0
while attempt < 3:
    print("attempt", attempt)
    attempt += 1

Example output:

attempt 0
attempt 1
attempt 2

In a for loop you rarely need to increment at all. range() does the counting. Its documented forms are range(stop) and range(start, stop, step), where start defaults to 0 and step defaults to 1. The stop value is never included, and a step of 0 raises ValueError:

list(range(1, 11))       # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list(range(0, 10, 3))    # [0, 3, 6, 9]

When you need both the item and its position, enumerate(iterable, start=0) supplies the count. The documentation's own example uses start=1 to number items from one. See Python range() examples and Python enumerate() examples for more.

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
for number, season in enumerate(seasons, start=1):
    print(number, season)

Example output:

1 Spring
2 Summer
3 Fall
4 Winter

Increment a dictionary value or list item

The target of += can be a name, an attribute or a subscription, so it works on list items and dictionary entries directly:

scores = [10, 20, 30]
scores[1] += 1
print(scores)          # [10, 21, 30]

stock = {"apples": 4}
stock["apples"] += 1
print(stock)           # {'apples': 5}

Incrementing a key that does not exist yet raises KeyError, because += has to read the old value first. For counting items, use stock.get(key, 0) + 1, collections.defaultdict(int) or collections.Counter. Our Counter examples article covers the last one.

The same works on attributes, which is how an object keeps its own counter:

class Visits:
    def __init__(self):
        self.count = 0

    def record(self):
        self.count += 1

Why += on a list behaves differently

For a list, += calls the object's in-place add. The Python FAQ states that for lists this is equivalent to calling extend() and returning the list. So the list changes in place, and every other name bound to the same list sees the change:

first = [1, 2]
second = first
first += [3]
print(second)          # [1, 2, 3]  (same list object)

first = first + [4]    # builds a new list and rebinds first
print(second)          # [1, 2, 3]  (unchanged)

That is the "not exactly equal" case the reference describes. With numbers and strings you will not notice it, but with lists passed into functions it can matter. The Python operators article has the wider picture.

The tuple trap

The FAQ documents a surprising case. Because augmented assignment ends with an assignment, using it on a tuple element raises an error even when the underlying list is changed:

>>> a_tuple = (['foo'], 'bar')
>>> a_tuple[0] += ['item']
Traceback (most recent call last):
   ...
TypeError: 'tuple' object does not support item assignment
>>> a_tuple[0]
['foo', 'item']

The list was extended, then the final store back into the tuple failed. To avoid this, call a_tuple[0].extend(['item']) instead, which changes the list without assigning into the tuple.

You cannot increment inside an expression

In C, count++ can sit inside a larger expression. In Python, += is a statement, so this fails:

print(count += 1)      # SyntaxError

Put the increment on its own line before or after the call. If you really need to assign inside an expression, the assignment expression := exists, but (count := count + 1) is rarely clearer than two lines.

If the counter does not change

  • You wrote ++x. It is valid and does nothing. Use x += 1.
  • UnboundLocalError inside a function. Assigning to a name makes it local to the function, so count += 1 on a module-level variable fails because the local count has no value yet. Pass the value in and return the new one, or keep the counter on an object as an attribute.
  • The value is a string. "5" += 1 style code, such as a number read with input(), raises TypeError. Convert first with int().
  • The new value is never used. x + 1 on its own line computes a result and throws it away. Only x += 1 or x = x + 1 stores it.

Frequently asked questions

Does Python have i++ or ++i?
No. Python has no increment or decrement operator. To add one, write i += 1. The expression ++i is valid syntax but does nothing, because it is read as unary plus applied twice, which returns the number unchanged.
How do I decrement by 1 in Python?
Use i -= 1. The same augmented assignment form exists for subtraction, multiplication, division and the other binary operators, so there is no separate decrement syntax.
What is the difference between x += 1 and x = x + 1?
For an integer they give the same result. The Python reference says the two have a similar but not exactly equal effect: with += the target is evaluated only once, and when the type supports it the operation is done in place on the existing object. That matters for lists, where += modifies the list instead of building a new one.
Can I increment inside an expression, like count++ in C?
Not with +=, because += is a statement, not an expression. You cannot write print(i += 1). Increment on its own line, or use enumerate() or range() so the loop supplies the counter for you.

Sources