Perform addition or concatenation through a callable.
What You Will Learn
add(left, right) has the same semantics as left + right; on sequences it concatenates instead of calculating a numeric sum.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from operator import add
print(add(3, 7))
print(add(['A'], ['B']))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: operator.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
10
['A', 'B']
Another Example: Compare the Results
Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.
from operator import add
print(add(10, 5), add("a", "b"))
Expected output:
15 ab
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Use add with reduce() to combine several numbers.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming add() always performs numeric arithmetic instead of type-specific addition.
- Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.
Key Takeaways
- Perform addition or concatenation through a callable.
- add(left, right) has the same semantics as left + right; on sequences it concatenates instead of calculating a numeric sum.
- Apply this operation only after checking the assumptions and input conditions shown in the example.