
Python tuple addition (concatenate tuples)
We can add Python tuples with an addition operator in the same way as numbers or strings addition.
t1 = ('A', 'B', 'C')
t2 = ('D', 'E')
t = t1 + t2
print(t) # ('A', 'B', 'C', 'D', 'E')
You can add multiple tuples at once.
a = (1, 2, 3)
b = (4, 5)
c = (6, 7, 8)
d = a + b + c
print(d)
# (1, 2, 3, 4, 5, 6, 7, 8)
A tuple and value can't be added
We can't add a tuple and a not-tuple value.
t1 = ('A', 'B', 'C')
t2 = 'D'
t = t1 + t2
# TypeError: can only concatenate tuple (not "str") to tuple
The tuple (?) containing only one value without a trailing comma can't be added to a tuple.
t1 = ('A', 'B', 'C')
t2 = (5)
t = t1 + t2
# TypeError: can only concatenate tuple (not "int") to tuple
In fact, (5)
is an integer, not a tuple.
t1 = ('A', 'B', 'C')
t2 = (5)
print(type(t2)) # <class 'int'>
But if it has a trailing comma, it is a tuple and added to another tuple.
t1 = ('A', 'B', 'C')
t2 = ('D',)
t = t1 + t2
print(t) # ('A', 'B', 'C', 'D')
Using asterisk
You can concatenate tuples using an asterisk (*
) operator.
a = (1, 2, 3)
b = (4, 5)
c = (*a, *b)
print(c)
# (1, 2, 3, 4, 5)
If putting tuples directly into round brackets, c
is a tuple containing two tuples and not containing directly those elements. Check the difference of the tuple and value generated by using the asterisk.
a = (1, 2, 3)
b = (4, 5)
print(a) # (1, 2, 3)
print(*a) # 1 2 3
Convert Python list to tuple
You can convert a Python list to a tuple as follows.
s = [1, 2, 3]
a = ()
for x in s:
a = a + (x,)
print(a)
# (1, 2, 3)
The important point is that each iterated value is enclosed with a trailing comma. If not so, each element is not a tuple and the TypeError will be raised.
Comments
Powered by Markdown