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.
1 2 3 4 |
a = 5 b = 4 c = a + b print(c) |
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:
1 2 3 4 |
str1 = "Hello" str2 = "World" result = str1 + " " + str2 print(result) |
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:
1 2 3 4 |
list1 = [1, 2, 3] list2 = [4, 5, 6] merged_list = list1 + list2 print(merged_list) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __str__(self): return f"({self.x}, {self.y})" p1 = Point(1, 2) p2 = Point(3, 4) print(p1 + p2) |
Running this will print:
(4, 6)
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Adding two numbers a = 5 b = 4 c = a + b print(c) # Concatenating two strings str1 = "Hello" str2 = "World" result = str1 + " " + str2 print(result) # Merging two lists list1 = [1, 2, 3] list2 = [4, 5, 6] merged_list = list1 + list2 print(merged_list) # Adding two custom objects class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __str__(self): return f"({self.x}, {self.y})" p1 = Point(1, 2) p2 = Point(3, 4) print(p1 + p2) |
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.