Add vs in-place add of str to list

R

rs387

Hi

I'm trying to understand why it is that I can do
['s', 't', 'u', 'f', 'f']

but not
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

Can someone explain the logic? Why is the in-place add not a type
error but the usual add is? (This applies to both Python 2.6rc1 and
3.0b2)

Thanks
Roman
 
R

rs387

It's because the `+=` operator is doing the equivalent of calling the
`extend` method, which treats its argument as a generic sequence, and
doesn't enforce type.

I see. Do you know whether this is seen as a problem with the language
design?

If so, this could be fixed by changing list.__add__ to call .extend on
the left argument if it's a list... Or, by changing __iadd__ to throw
a TypeError, whichever way around is seen as more correct/desirable.
 
M

Mel

rs387 said:
I see. Do you know whether this is seen as a problem with the language
design?

No.

[1,2,3] + [4,5,6]

produces

[1,2,3,4,5,6]

not

[1,2,3,[4,5,6]]

Mel.
 
R

rs387


OK, I get it now. I was assuming that the "+" could be implemented in
terms of "+=" as follows:

def add(x,y):
temp = list(x)
temp += y
return temp

But it turns out that this is not what "+" means at all. A bit of a
gotcha...

Roman
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top