They don’t know. Knowing doesn’t affect your external appearance. In this case, the caterpillars look like snakes because birds and other predators ate the ones that didn’t look very much like snakes, leaving only the ones that looked like snakes.
This only works as long as there’s sufficient variety in how the caterpillars look that there are some that look kind of like snakes and some that don’t look very much like snakes for the predators to go for. All populations include variation between individuals.
Latest Answers