Prefix codes are instantaneously decodable. This minimality constraint prevents codewords from being longer than they need to be. The mapping from messages to codewords is static. The above two examples are static. The mapping of messages to codewords changes as the encoding process proceeds.
Some static codes require two passes.
They also require that the mapping be stored or transmitted with the encoded ensemble. Note that the greater the probability of occurrence the smaller the number of bits. This whole idea is easier to see if we look at some idealized examples. As just mentioned, if we have just 1 message with a probability of 1 then we need no bits to encode it.