Search the difference: Why this function defenition does'nt work?

Luke LLoeffler at home.com
Sun Dec 23 11:24:38 EST 2001


['c'] is a *list* with a character in it.

You can do this [1,2,3] + [1]
but not this [1,2,3] + 'a'

because the first example is concatenating two lists; the second is a 
list and a string.  Your summing code is taking a list and then 
appending strings (single character ones at that) to it.

It has something to do with how + is implemented... Each type of object 
implements something like __concat__ (I don't know if this is correct or 
not--I'm just guessing) which gets called when python sees a +.  It 
expects to see another object of its own type passed to it.  Imagine if 
you were the developer writing a concatenation function to concatenate a 
string type with a list... Say [1,2,3] + "abc".  Do you do this: 
[1,2,3,"abc"] or do you do this: [1,2,3,'a','b','c'].  It is ambiguous.

Luke


> But when I adjust the code to this:
> 
> sum=['c']
> 
> it still does not work, despite the fact that sum is not an undefined 
> object, right?
> 
> 
> 




More information about the Python-list mailing list