Have you ever written code like this?
Python
total = total + price
It works, but it’s a bit long and repetitive. Python has a better way: the += operator.
The += operator adds a value to a variable and saves the result in the same variable, all in one step. It makes your code shorter, cleaner, and easier to read.
In this guide, you’ll learn how += operator works, see examples for different data types, and discover practical ways to use it in Python.
What is the += Operator?
The += operator combines addition and assignment into one step. For example:
Python
# Increment count by 5
count = 10
count += 5
print(count)
Output:
15
Here’s what happens step by step:
- Python looks at the current value of count, which is 10.
- It adds 5 to that value.
- It stores the result back in the same variable, count.
So instead of repeating the variable name like count = count + 5, you can use += to make it cleaner.
Using += with Different Data Types
1. Numbers (Integers or Floats)
For numbers, += simply adds the right-hand value to the left-hand variable.
Python
# Increment score by 25
score = 100
score += 25
print(score)
Output:
125
Explanation:
- score starts at 100.
- The += operator adds 25 to it.
- The new value 125 is saved back into score.
This is helpful when you want to keep a running total, like tracking points in a game or calculating expenses.
2. Strings (Text)
When used with strings, += joins one string to another.
Python
# Append text to greeting
greeting = "Hello"
greeting += ", Python!"
print(greeting)
Output:
Hello, Python!
Explanation:
- greeting starts as “Hello”.
- The += operator adds “, Python!” to the end.
- Python creates a new string “Hello, Python!” and stores it back in greeting.
Note: Strings are immutable in Python, so every time you use += with strings, a new string is created in memory. For short strings or a few additions, this is fine. For long loops, consider using a list and join() for better performance.
3. Lists (Collections of Items)
With lists, += adds elements from another list.
Python
# Extend todo_list with new tasks
todo_list = ["code", "test"]
todo_list += ["debug", "deploy"]
print(todo_list)
Output:
[‘code’, ‘test’, ‘debug’, ‘deploy’]
Explanation:
- todo_list originally contains [“code”, “test”].
- += adds the new items [“debug”, “deploy”] to the same list.
- The list is updated in place, so no new list is created.
This is very handy when you want to combine multiple lists quickly, like merging inventory or task lists.
Note: You cannot use += directly on tuples because tuples are immutable.
Real-Life Examples
1. Summing Numbers in a Loop
Python
# Calculate total cost of prices
total_cost = 0
prices = [2.99, 4.50, 1.25]
for price in prices:
total_cost += price
print(f"Total: ${total_cost:.2f}")
Output:
Total: $8.74
Explanation:
- total_cost starts at 0.
- The loop goes through each item in the prices list.
- Each price is added to total_cost using +=.
- After the loop, total_cost contains the sum of all prices.
This is much cleaner than writing total_cost = total_cost + price for each item.
2. Conditional Updates
Python
# Add points if level completed
player_points = 0
level_completed = True
if level_completed:
player_points += 50
print(player_points)
Output:
50
Explanation:
- player_points starts at 0.
- The condition if level_completed: checks if the player finished a level.
- If True, 50 points are added using +=.
- The result 50 is stored back in player_points.
This is useful when you want to update a value only under certain conditions.
3. Updating Lists
Python
# Extend inventory with new items
inventory = ["laptop", "mouse"]
new_items = ["keyboard", "monitor"]
inventory += new_items
print(inventory)
Output:
[‘laptop’, ‘mouse’, ‘keyboard’, ‘monitor’]
Explanation:
- inventory contains two items.
- += adds the new_items list to inventory.
- The list is updated in place.
This makes it simple to merge lists without writing long code.
Common Mistakes to Avoid
1. Mixing Types
Python
# Error: cannot add string to integer
count = 10
count += "5"
Why it fails: Python cannot add a number (int) and a string.
Fix: Convert the string to a number first:
Python
# Convert string "5" to int before adding
count += int("5")
output:
15
Always check your variable types when using +=.
2. Inefficient String Concatenation in Loops
Python
# Slow approach: concatenating strings in a loop
log = ""
for i in range(1000):
log += str(i) # Slow for large loops
# Better approach: use a list and join
log_parts = []
for i in range(1000):
log_parts.append(str(i))
log = "".join(log_parts)
Explanation: Using += repeatedly with strings creates many temporary strings in memory. Using a list and join() is faster for large loops.
Tips for Using +=
1. Use for clarity: Only use += where it makes code simpler.
2. Break complex calculations into steps:
Python
# Hard to read
distance = speed * time
distance += acceleration * time ** 2 / 2
# Easy to read
base = speed * time
adjust = acceleration * time ** 2 / 2
distance = base + adjust
3. Use with loops and lists: Great for totals, concatenation, and combining items.
Also Read
Convert an integer to a string in Python
Python switch statement
JavaScript vs Python
Conclusion
The += operator is small but powerful. It:
- Saves lines of code
- Makes code readable
- Works with numbers, strings, and lists
Next time you see x = x + y, think about replacing it with x += y. It keeps your Python code clean and simple.