Python add item to the tuple

Question:

I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like (u'2',) but when I try to add new one using mytuple = mytuple + new.id got error can only concatenate tuple (not "unicode") to tuple.

Asked By: Goran

||

Answers:

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

a = ('2',)
b = 'z'
new = a + (b,)
Answered By: Jon Clements
>>> x = (u'2',)
>>> x += u"random string"

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", )  # concatenate a one-tuple instead
>>> x
(u'2', u'random string')
Answered By: jamylak

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 can’t change a tuple. So you have to create a new one.

Answered By: kiriloff

Tuple can only allow adding tuple to it. The best way to do it is:

mytuple =(u'2',)
mytuple +=(new.id,)

I tried the same scenario with the below data it all seems to be working fine.

>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')
Answered By: Raul Kiran Gaddam

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

a = ('2',)
b = 'z'
new = (*a, b)
Answered By: nitely

#1 form

a = ('x', 'y')
b = a + ('z',)
print(b)

#2 form

a = ('x', 'y')
b = a + tuple('b')
print(b)
Answered By: britodfbr

Bottom line, the easiest way to append to a tuple is to enclose the element being added with parentheses and a comma.

t = ('a', 4, 'string')
t = t + (5.0,)
print(t)

out: ('a', 4, 'string', 5.0)
Answered By: alphahmed

If the comma bugs you, you can specify it’s a tuple using tuple().

ex_tuple = ('a', 'b')
ex_tuple += tuple('c')
print(ex_tuple)
Answered By: Thomas
tup = (23, 2, 4, 5, 6, 8)
n_tup = tuple(map(lambda x: x+3, tup))
print(n_tup)
Answered By: Amol Ugale

my favorite:

myTuple = tuple(list(myTuple).append(newItem))

Yes, I know it is expensive, but it sure looks cool 🙂

Answered By: ShellDude
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.