In Python, as in many programming languages, there is a need to increment variables. The process of incrementing is a short way to add a specific value to a variable. This guide will focus on explaining different ways of incrementing values in Python.
Before We Begin
It is important to understand that Python does not support the “++” and “–” increment/decrement operators you might know from other languages like C++ or Java. We will go over the alternatives Python provides.
Simple Incrementing
In Python, you can increment a variable in the following way:
1 2 3 4 |
# Given a = 1 # Increment a = a + 1 |
After this code, the value of a will be 2. We simply take the old value of a, add 1 to it and save it back to a.
Shorthand Incrementing
Python provides a shorthand way to do the same thing:
1 2 3 4 |
# Given a = 1 # Increment a += 1 |
The a += 1 statement is equivalent to a = a + 1 but it’s shorter and more readable, especially when used in longer computations.
Incrementing Non-Numerical Values
Incrementing does not work on non-numerical values, like strings or lists, in the same way as on numerical values. But those types do have their equivalent of “incrementing”. For example, you can add a string to a string:
1 2 3 4 |
# Given s = "Hello" # Increment s += " World" |
Or you can add an item to a list:
1 2 3 4 |
# Given l = [1, 2, 3] # Increment l += [4] |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Simple incrementing a = 1 a = a + 1 print(a) # Shorthand incrementing a = 1 a += 1 print(a) # String incrementing s = "Hello" s += " World" print(a) # List incrementing l = [1, 2, 3] l += [4] print(a) |
Output:
2 2 2 2
Conclusion
In this tutorial, we have learned several ways to increment variables in Python. Remember, Python does not use “++” or “–“, so always use the “+=” operator or the long form “variable = variable + value”. You can also increment strings and lists, not only numerical variables. Continue your studies on the official Python documentation.