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 :)