Python Gotcha's?
Evan Driscoll
driscoll at cs.wisc.edu
Thu Apr 5 18:11:47 EDT 2012
More information about the Python-list mailing list
Thu Apr 5 18:11:47 EDT 2012
- Previous message (by thread): Python Gotcha's?
- Next message (by thread): Python Gotcha's?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 4/5/2012 13:44, Michael Hrivnak wrote: > This is not a gotcha, and it's not surprising. As John described, > you're assigning a new value to an index of a tuple, which tuples > don't support. Um, at least for me personally, yes, it is surprising, and yes, it is a gotcha. This goes back to what languages you're used to. I come from a strong C++ background. In C++, something like mytuple[0] += [3] would wind up calling 'operator+=' on the list, that += would mutate the list, and then the expression would be done. The C++ approach doesn't really work with Python because more stuff is immutable, and Python's behavior is arguably the least-bad solution, but it WAS definitely surprising for me (and others!) when I learned about Python's behavior. In particular, the translation of 'a+=b' to 'temp = a + b; a = temp' is *not* a very natural one to me. Evan > > Michael > > On Thu, Apr 5, 2012 at 10:15 AM, John Posner <jjposner at optimum.net> wrote: >> On 4/4/2012 7:32 PM, Chris Angelico wrote: >>> Don't know if it's what's meant on that page by the +=perator, >> >> Yes, it is. >> >>>> a=1],) >>>> a[0].append(2) # This is fine >> >> [In the following, I use the term "name" rather loosely.] >> >> The append() method attempts to modify the object whose name is "a[0]". >> That object is a LIST, so the attempt succeeds. >> >>>> a[0]+=] # This is not. >> >> The assignment attempts to modify the object whose name is "a". That >> object is a TUPLE, so the attempt fails. This might be a surprise, but >> I'm not sure it deserves to be called a wart. >> >> Note the similarity to: >> >> temp =[0] + [3] # succeeds >> a[0] =emp # fails >> >> -John >> >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 552 bytes Desc: OpenPGP digital signature URL: <http://mail.python.org/pipermail/python-list/attachments/20120405/76bf4520/attachment-0001.sig>
- Previous message (by thread): Python Gotcha's?
- Next message (by thread): Python Gotcha's?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list