Python add item to the tuple

Python add item to the tuple

You need to make the second element a 1-tuple, eg:

a = (2,)
b = z
new = a + (b,)

Since Python 3.5 (PEP 448) you can do unpacking within a tuple, list set, and dict:

a = (2,)
b = z
new = (*a, b)

Python add item to the tuple

From tuple to list to tuple :

a = (2,)
b = b

l = list(a)
l.append(b)

tuple(l)

Or with a longer list of items to append

a = (2,)
items = [o, k, d, o]

l = list(a)

for x in items:
    l.append(x)

print tuple(l)

gives you

>>> 
(2, o, k, d, o)

The point here is: List is a mutable sequence type. So you can change a given list by adding or removing elements. Tuple is an immutable sequence type. You cant change a tuple. So you have to create a new one.

Leave a Reply

Your email address will not be published. Required fields are marked *