Why is this?

Peter Mott peter at monicol.co.uk
Fri Aug 12 12:06:45 EDT 2005


Matt Hammond wrote:
> On Fri, 12 Aug 2005 12:57:38 +0100, Peter Mott <peter at monicol.co.uk> wrote:
> 
>> If I use concatenation + instead of multiplication * then I get the  
>> result that Jiri expected:
>>
>>  >>> L = [[]] + [[]]
>>  >>> L[1].append(1)
>>  >>> L
>> [[], [1]]
>>
>> With * both elements are changed:
>>
>>  >>> L = [[]] * 2
>>  >>> L[1].append(1)
>>  >>> L
>> [[1], [1]]
>>
>> Alex Martelli says in his excellent Nutshell book that + is  
>> concatenation and that "n*S is the concatenation of n copies of S". 
>> But  it seems not so. Surely, from a logical point of view, S + S 
>> should be  the same as S * 2?
> 
> 
> S+S is the same as S*2, but L= [[]] + [[]] is not S+S. The two terms 
> being  added are different instances of an empty list. You are  
> adding/concatenating two different object instances.

But it is still true that [[]] + [[]] is not the same as [[]] * 2. In my 
usage anyway this means that "S+S is the same as S*2" is false. Because 
there are Python expressions for which it is falsfied.

The problem I have is pretty philosophical I admit, but I don't think 
you do it justice. It's really about identity. Logically speaking 
identity is a congruence relation of a language, which means that if x=y 
is true then C(x) = C(y) will be true for any context C of the lanuage. 
Python is so regular that most of the time it follows this. But not with 
*. If you define C(x):

def C(x):
... 	x[1].append(1)
... 	return x[0]

then although [[]]+[[]] == [[]]*2 evaluates true  C([[]]+[[]]) is 
different from C([[]]*2). So == is not a congruence in Python. 
Inbteresting that Phil Hunt just posted about 'Unify' which, if I 
understand it right, has the feature that provided expressions S and T 
are in the canonical "Storage Manager" format then == will be a 
congruence and hence an idenity.

Cheers

Peter



More information about the Python-list mailing list