 The Hamiltonian expression of the momenta of the system can be derived from the Lagrangian, and vice versa, using a Legendre transform. In fact, the Hamiltonian just is the Legendre transform of the Lagrangian for any given system. The formalisms are equivalent, but there are some situations, including evaluating heat transfer, in which the Hamiltonian is preferred.