I'm one of the teaching assistants (TA) for 6.00 this semester. Another TA sent this to our mailing list:
This is just for your amusement. I came across an interesting quirk of python.
First the normal stuff:
>>> [1,2,3] + [4] [1,2,3,4] >>> (1,2,3) + (4,) (1,2,3,4) >>> (1,2,3) + [4] Traceback (most recent call last): File "", line 1, in (1,2,3) + [4] TypeError: can only concatenate tuple (not "list") to tuple >>> [1,2,3] + (4,) Traceback (most recent call last): File " ", line 1, in [1,2,3] + (4,) TypeError: can only concatenate list (not "tuple") to list >>> l = [1,2,3] >>> l + (4,) Traceback (most recent call last): File " ", line 1, in l + (4,) TypeError: can only concatenate list (not "tuple") to list
So far so good, but now:
>>> l += (4,) >>> l [1, 2, 3, 4]
But it's not symmetric:
>>> l = (1,2,3) >>> l += [4] Traceback (most recent call last): File "", line 1, in l += [4] TypeError: can only concatenate tuple (not "list") to tuple
Which is to say, list's __iadd__ function is polymorphic to tuples, but
tuple's isn't to lists, and list's __add__ isn't either. Odd and a little
ugly, but yeah. Anyone know whether this is a bug or a feature?
0 comments:
Post a Comment