They do this using the refrigeration cycle. On the heating side a refrigerant evaporates and gains heat.
On the cooling side it is condensed and gives off that heat. This happens is a loop. One side of the loop is in your house and the other is outside. When the seasons change the process can be reversed. This is of course a major simplification. There are laws of thermodynamics in play with lots of charts and complex math to go along with it.
One way to think about it is this. The refrigerant is normally in a vapour form. All the little particles that make up the vapour have lots of energy they are far apart and are moving around very fast. That’s what makes them a vapour. A compressor is used to squeeze that vapour down. When this happens the little particles get closer together and can’t move around as much. They have to give some energy away. They do this by condensing into a liquid and giving off heat.
Next they flow through a valve to the other side of the loop and expand again. They become a vapour or “evaporate”. To do this they must gain energy. So they pull that energy or heat from their surroundings. Now they are an energetic vapour again. It’s back to the compressor and the cycle repeats. They are cold on one side and warm on the other.