Python Addition Operator

Rate this post

Python provides the addition operator + to add two objects. The semantics of the addition depends on the operands’ data types. For example, adding two integers perform arithmetic addition whereas adding two lists performs list concatenation. The specific return value of the addition operator is defined in a data types’ __add__() magic method.

Python Addition Operator - Deep Dive

Have a look at the following examples!


The + operator on integer operands yields another integer—the mathematical sum of both operands:

>>> 2 + 2
>>> 2 + 3
>>> -99 + (-1)

If at least one of the operands is a float value, the result is also a float—float is infectious!

>>> 2.0 + 1
>>> 1 + 2.2
>>> 2.0 + 40.0

Can we add strings? Of course! The result is a new string from gluing the second string to the first. This is called string concatenation:

>>> 'learn' + ' python'
'learn python'
>>> 'fi' + 'nxter'

If the operands are lists, the result of the addition operation is another list. It creates a new list with the elements of the first list plus the elements of the second list. The original lists remain unchanged.

>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> l1 = ['alice']
>>> l2 = ['ann', 'bob']
>>> l1 + l2
['alice', 'ann', 'bob']
>>> l1
>>> l2
['ann', 'bob']

What if two operands have an incompatible data type—unlike floats and integers? For example, if you try to add a string to a list?

>>> 'hello' + ['world']
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    'hello' + ['world']
TypeError: can only concatenate str (not "list") to str

The result of incompatible addition is a TypeError. You can fix it by using only compatible data types for the addition operation.

Can you use the addition operator on custom objects? Yes!

Python Addition Magic Method

To use the addition operator on custom objects, you need to define the __add__() dunder method that takes two arguments: self and other and returns the result of self + other. To obtain the result for a custom object, you can use the attributes (data) maintained in this object.

In the following code, you add two baskets together by combining their contents:

class Basket:
    def __init__(self, contents):
        self.contents = contents

    def __add__(self, other):
        return Basket(self.contents + other.contents)

my_basket = Basket(['banana', 'apple', 'juice'])
your_basket = Basket(['bred', 'butter'])

our_basket = my_basket + your_basket

The output of this code snippet is the combined basket:

['banana', 'apple', 'juice', 'bred', 'butter']

The code consists of the following steps:

  • Create the class Basket that holds the list contents to store some goods.
  • Define the magic method __add__ that creates a new Basket by combining the list of goods (contents) from the two operand baskets. Note that we rely on the already implemented addition operator on lists, i.e., list concatenation, to actually implement the addition operator for baskets.
  • We create two baskets my_basket and your_basket, and add them together to a new basket our_basket using the defined addition operation.

Python Addition Program with User Input

To create a simple addition program in Python taking the user’s input and adding together the provided numbers, you can use the following four steps:

  1. Get the user input as a string using the built-in input() function, and store the result in variables num_1 and num_2.
  2. Convert the string user inputs to numerical types using, for example, the int() or float() constructors.
  3. Add together the numerical values using the addition operator num_1 + num_2.
  4. Print the result to the Python shell.

Here are those four steps in Python code:

# Python addition program with user input

# 1. Get string user inputs representing integers
num_1 = input('First number: ')
num_2 = input('Second number: ')

# 2. Converting strings to ints
num_1 = int(num_1)
num_2 = int(num_2)

# 3. Adding numbers
result = num_1 + num_2

# 4. Display the result
print(num_1, '+', num_2, '=', result)

Here’s an example code execution where I put in integers 40 and 2 and calculated the sum of both using the addition operator:

First number: 40
Second number: 2
40 + 2 = 42

Python Addition Operator Chaining

You can chain together two addition operators. For example, the expression x + y + z would first add together x and y and then add z to the resulting object. Thus, it is semantically identical to ((x + y) + z).

Here’s a minimal example:

>>> x = 10
>>> y = 5
>>> z = 2
>>> x + y + z
>>> ((x + y) + z)

Arithmetic Operators

Arithmetic operators are syntactical shortcuts to perform basic mathematical operations on numbers.

+AdditionCalculating the sum of the two operands3 + 4 == 7
SubtractionSubtracting the second operand from the first operand4 - 3 == 1
*MultiplicationMultiplying the first with the second operand3 * 4 == 12
/DivisionDividing the first by the second operand3 / 4 == 0.75
%ModuloCalculating the remainder when dividing the first by the second operand7 % 4 == 3
//Integer Division, Floor DivisionDividing the first operand by the second operand and rounding the result down to the next integer8 // 3 == 2
**ExponentRaising the first operand to the power of the second operand2 ** 3 == 8