473,545 Members | 1,650 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Add vs in-place add of str to list

Hi

I'm trying to understand why it is that I can do
>>a = []
a += 'stuff'
a
['s', 't', 'u', 'f', 'f']

but not
>>a = []
a = a + 'stuff'
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
Oct 2 '08 #1
4 1523
rs387 wrote:
I'm trying to understand why it is that I can do
>>>a = []
a += 'stuff'
a
['s', 't', 'u', 'f', 'f']

but not
>>>a = []
a = a + 'stuff'
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)
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. The same thing happens with any other sequence
type as the right-hand operand; for instance, tuples:
>>a = []
a += (1, 2, 3)
a
[1, 2, 3]
>>a = []
a = a + (1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can only concatenate list (not "tuple") to list

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
Man is a hating rather than a loving animal.
-- Rebecca West
Oct 2 '08 #2
On Oct 2, 8:11*am, Erik Max Francis <m...@alcyone.c omwrote:
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.
Oct 2 '08 #3
Mel
rs387 wrote:
On Oct 2, 8:11Â*am, Erik Max Francis <m...@alcyone.c omwrote:
>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?
No.

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

produces

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

not

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

Mel.

Oct 2 '08 #4
On Oct 2, 3:50*pm, Mel <mwil...@the-wire.comwrote:
rs387 wrote:
I see. Do you know whether this is seen as a problem with the language
design?

No.
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
Oct 2 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6746
by: Curious Expatriate | last post by:
Hi- I'm completely stumped. I'm trying to write some code that will parse a file and rewrite it with all URLs replaced by something else. For example: if the file looks like this: <b>click here</b><a href="http://www.cnn.com">click me</a> ... then the output should be this:
1
6245
by: JS Bangs | last post by:
I started using PHP's object-oriented stuff a little while ago, which has mostly been a joy. However, I've noticed that they don't seem to echo as I would like. Eg: $this->field = 255; $this->key = 'id'; echo "$this->key is $this->field"; // prints "id is Array" // Thus I am forced to do this $keyval = $this->field;
5
16142
by: lawrence | last post by:
I've waited 6 weeks for an answer to my other question and still no luck, so let me rephrase the question. I know I can do this: <form method="post" action="$self"> <input type="text" name="filesToDelete"> <input type="text" name="filesToDelete"> <input type="text" name="filesToDelete"> </form>
0
4906
by: Ben Eisenberg | last post by:
I'm trying to run a php script setuid. I've tried POSIX_setuid but you have to be root to run this. The files are located on a public access unix system and have me as the owner and nobody as the group. Rather than make them group writable where in anybody could make a script and write to my files i would like to make them setuid. I tried...
2
8549
by: Felix | last post by:
Hi, I've a problem: I want to have the result of my Mysql Query in a Table in my php file. Now I've this: <?
1
8698
by: James | last post by:
What is the best way to update a record in a MYSQL DB using a FORM and PHP ? Where ID = $ID ! Any examples or URLS ? Thanks
1
2936
by: Patrick Schlaepfer | last post by:
Why this code is not working on Solaris 2.8 host. Always getting: PHP Fatal error: swfaction() : getURL('http://www.php.net' ^ Line 1: Reason: 'syntax error' in /.../htdocs/ming2.php on line 28
1
3406
by: phpkid | last post by:
Howdy I've been given conflicting answers about search engines picking up urls like: http://mysite.com/index.php?var1=1&var2=2&var3=3 Do search engines pick up these urls? I've been considering converting a site of mine to PHP-Nuke, but if the individual modules aren't picked up in search engines I'm not going to do it. Thanks phpKid
1
2550
by: lawrence | last post by:
What is the PHP equivalent of messaging, as in Java?
3
4904
by: Quinten Carlson | last post by:
Is there a way to conditionally define a function in php? I'm trying to run a php page 10 times using the include statement, but I get an error because my function is already defined. The docs state that a function cannot be undefined and adding "exit" to the included page doesn't free it up either. Any suggestions? B44CCD21
0
7459
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7803
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7411
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5322
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4942
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3439
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1871
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1012
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
695
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.