# Change the cost function in the ExpvalCost

**URL:** <https://discuss.pennylane.ai/t/change-the-cost-function-in-the-expvalcost/1050>\
**Category:** PennyLane Help\
**Created:** [May 17, 2021, 11:04pm UTC](https://discuss.pennylane.ai/t/change-the-cost-function-in-the-expvalcost/1050 "2021-05-17T23:04:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Einar\_Gabbassov](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/einar_gabbassov/32/576_2.png) [@Einar\_Gabbassov](https://discuss.pennylane.ai/u/Einar_Gabbassov)\
**Post date:** [May 17, 2021, 11:04pm UTC](https://discuss.pennylane.ai/t/change-the-cost-function-in-the-expvalcost/1050/1 "2021-05-17T23:04:14Z")

</div>

Hi,  
I’m new to the pennylane API. So far it looks great!  
I was working through the [VQE tutorial](https://pennylane.ai/qml/demos/tutorial_vqe.html).  
My question is about changing the content of `cost_fn` attribute of an object of the `ExpvalCost` class. Specifically, I would like to change the cost function. For example, I have:

```
cost_fn_1 = qml.ExpvalCost(circuit, hamiltonian_1, dev)
cost_fn_2 = qml.ExpvalCost(circuit, hamiltonian_2, dev)

```

Now I want to add the cost function of the object `cost_fn_2` to the cost function of the object `cost_fn_1` like so

```
cost_fn_1.cost_fn = cost_fn_1.cost_fn + foo*cost_fn_2.cost_fn - C

```

where `foo` and `C` are some variables. The above code gives an error because I’m trying to add `function` types.  
So the solution was to create a lambda function like so:

```
final_cost_fn = lambda x: cost_fn_1.cost_fn(x) + foo*cost_fn_2.cost_fn(x) - C

```

And then assigning `final_cost_fn` as so

```
 cost_fn_1.cost_fn = final_cost_fn

```

This approach works, but I’m not sure if this is the best way of altering the cost function given that this object will be further used by optimizers and other pennylane objects.

Thank you

---

<div class="post-metadata">

**Author:** ![josh](https://yyz2.discourse-cdn.com/flex012/user_avatar/discuss.pennylane.ai/josh/32/100_2.png) [@josh](https://discuss.pennylane.ai/u/josh)\
**Post date:** [May 18, 2021, 6:43am UTC](https://discuss.pennylane.ai/t/change-the-cost-function-in-the-expvalcost/1050/2 "2021-05-18T06:43:09Z")

</div>

Hi @Einar_Gabbassov! Welcome.

> So the solution was to create a lambda function like so… This approach works, but I’m not sure if this is the best way of altering the cost function given that this object will be further used by optimizers and other pennylane objects.

The approach you have for extending the cost function is the recommended approach 🙂

Let us know if you run into any issues with this approach!
