“+” adds as well as concatenates in Python | WHY ?

When “+” is used between two integers, the integers get added and when the same operator is used between two strings, the strings get concatenated as depicted:

Now what makes these two operations different is the question to answer here. A general answer to the question is that in case of addition the operands are of integer type while in the matter of concatenation both operands are of string type so this is why the same operator behaves differently.

This is all right but to technically justify and complete the answer one needs to know about the following; magic methods and the concept of syntatic sugar in programming.

Briefly put, magic methods are special built-in methods of the built-in classes in python. Magic methods start and end with double underscores and these methods aren’t invoked directly by the programmer rather upon a certain action done by programmer these are invoked respectively, for instance __add__ method from int class in python. Syntatic sugar refers to making the syntax simplified to use for application programmers.

Both these two concepts combined answer our question. Following snippets will elaborate the difference between earlier showed code snippets:

As shown, to illustrate the concept, we’re directly invoking the __add__ method from int class for operands addition and __add__ method from str class from str class for operands concatenation and it outputs the same result. Hence technically it is showed that when the operands are integers, the + operator will invoke int.__add__ and when the operands are strings, then str.__add__ will be invoked by putting + operator which is nothing but the synthetic sugar in play invoking two different methods based on a certain condition.

17