Showing posts with label tuples. Show all posts
Showing posts with label tuples. Show all posts

Thursday, July 5, 2018

How do you concatenate tuples in Python?

You cannot concatenate data types such as 'int', 'string' etc. to a tuple. However, you can concatenate two tuples.

Review the following code:
>>> t=12, -34, 'hi', True
>>> t
(12, -34, 'hi', True)
t is a tuple.
------------
>>> b=13,45,56
>>> b
(13, 45, 56)
b is another tuple
----------------
>>> g=t+b
>>> g
(12, -34, 'hi', True, 13, 45, 56)
Tuple g is obtained by concatenating t and b
-------------
>>> c=555,444
>>> c
(555, 444)
C is another tuple
You can do this:
>>> g += c
>>> g
(12, -34, 'hi', True, 13, 45, 56, 555, 444)
--------------------------
If you try to concatenate a list to a tuple you will get this error:
Traceback (most recent call last):
  File "", line 1, in
    c+lst2
TypeError: can only concatenate tuple (not "list") to tuple