Most of these housing codes have one of two reasons for them - keeping poor people from moving into the richer neighborhood by living together, and keeping other undesirable groups like college students or vacationers near beach towns from either living in crowded noisy houses that disturb the neighbors or fail to make enough money for landlords.
Some of it’s also leftover Puritanism, because if groups of people are living together who aren’t family, they might be (gasp!) couples (or worse!) having sex outside of marriage, and we simply can’t allow that to go on!
And in case it’s not obvious, just because these are reasons doesn’t mean I think they’re good reasons. And I’ve had friends here in Silicon Valley deal with the housing situation by sharing houses, especially if they were single when they moved here, which many recent college graduates were.