Why are asteroids and comets such weird shapes?

A rubber duck. A spinning top. A pair of pancakes. These are just a few of the shapes astronomers have observed across the solar system.

While planets and some moons are almost perfectly spherical, the smaller bits of the solar system, such as asteroids and comets, come in all different shapes. But why is that?