diff --git a/pennylane/pauli/pauli_arithmetic.py b/pennylane/pauli/pauli_arithmetic.py index 69fe9ebd528..a509baeb931 100644 --- a/pennylane/pauli/pauli_arithmetic.py +++ b/pennylane/pauli/pauli_arithmetic.py @@ -342,6 +342,18 @@ def __add__(self, other): larger_ps[key] += smaller_ps[key] return larger_ps + + def __iadd__(self, other): + """Adding two Pauli sentence together in-place by iterating over the smaller + one and adding its terms to the larger one, modifying self in place""" + smaller_ps, larger_ps = (self, other) if len(self) < len(other) else (other, self) + for key in smaller_ps: + if key in self: + self[key]+=smaller_ps[key] + else: + self[key]=smaller_ps[key] + + return self # Return self to indicate in-place modification def __copy__(self): """Copy the PauliSentence instance.""" diff --git a/tests/pauli/test_pauli_arithmetic.py b/tests/pauli/test_pauli_arithmetic.py index 86a5b429641..a363ac082b6 100644 --- a/tests/pauli/test_pauli_arithmetic.py +++ b/tests/pauli/test_pauli_arithmetic.py @@ -409,6 +409,16 @@ def test_add(self, string1, string2, result): (ps5, "Can't get the matrix of an empty PauliSentence."), ) + @pytest.mark.parametrize("string1, string2, result", tup_ps_add) + def test_iadd(self, string1, string2, result): + """Test that the correct result of inplace-addition is produced.""" + original_string2 = copy(string2) + string1 += string2 # Perform in-place addition using += + string1.simplify() + + assert string1 == result # Check if the modified object matches the expected result + assert original_string2 == string2 # Ensure the original object is not modified + @pytest.mark.parametrize("ps, match", ps_match) def test_to_mat_error_empty(self, ps, match): """Test that an appropriate error is raised when an empty