Tuple + Tuple?
by kiawin
An interesting trivial task is to concatenate two tuples in python.
Let’s say we try this out:
a = ('dd')
b = ('aa','bb')
print a+b
Unfortunately likely we will get the following error:
Traceback (most recent call last):
File "test.py", line 20, in <module>
print a+b
TypeError: cannot concatenate 'str' and 'tuple' objects
Interestingly, adding a comma after the value in first tuple, will resolve this issue:
a = ('dd',)
b = ('aa','bb')
print a+b
If you look carefully at the error thrown, you will know that actually String in python actually is treated as a tuple.
TypeError: cannot concatenate ‘str’ and ‘tuple’ objects
Hence leads to the “anticipated” TypeError if we attempt to concatenate a string and a tuple object :)
Comments
What you’re seeing here is a Python syntax implementation detail. Because Python could not otherwise disambiguate between parenthesis for operator precedence and tuples in the first case.
Hence:
a = () # tuple
b = (‘a’) # string, also (1 + 2) and (1 + 2) / 3
c = (‘a’,) # tuple