How to Add Two Objects in Python

In Python, objects can range from simple data types, such as strings and integers, to more complex types, like classes and modules. Sometimes, you may need to add or concatenate two objects together, whether it be two text strings, two lists, or even two custom objects from a class you’ve created.

In this tutorial, we’ll explore how you can add two objects together in Python, discussing everything from numbers and strings to the more complex types.

Step 1: Adding Two Numbers

Combining two numeric objects is straightforward. Python makes it simple to add two numbers together using the + operator. Let’s take two integer values for example.

This script will output:

9

Step 2: Concatenating Two Strings

You can also use the + operator to concatenate two string objects. Consider the following example:

Upon running this script, we get:

Hello World

Step 3: Merging Two Lists

Similarly, two list objects can be merged using the + operator. Here’s how:

The output would be:

[1, 2, 3, 4, 5, 6]

Step 4: Adding Two Custom Objects

When it comes to adding two custom objects, things can get a bit more complex. This process involves creating a special method, __add__(), inside your class definition. Check out Python’s documentation to learn more about these ‘dunder’ methods.

Running this will print:

(4, 6)

Full Code

Conclusion

The ability to ‘add’ or combine two objects fundamentally depends on the type of objects you are dealing with. For simple data types like numbers and strings, and even some complex types like lists, Python makes it simple through the + operator.

But for custom objects, you will need to define how the objects should be combined through appropriate method overloading. Whatever your object types, Python provides the flexibility and power needed to perform your desired operations.