'11' + '1' is '111'?
MRAB
python at mrabarnett.plus.com
Thu Oct 29 21:18:39 EDT 2009
Benjamin Peterson wrote:
> metal <metal29a <at> gmail.com> writes:
>
>> '11' + '1' == '111' is well known.
>>
>> but it suprises me '11'+'1' IS '111'.
>>
>> Why? Obviously they are two differnt object.
>>
>> Is this special feature of imutable object?
>
> As other posters have pointed out, CPython does cache some small strings. In
> this case, however, it's because '1' + '11' is constant folded.
>
It's also easy to fool the constant folding:
>>> '11' + '1' is '111'
True
>>> '11' * 1 + '1' is '111'
True
>>> '11' + '1' * 1 is '111'
False
More information about the Python-list
mailing list