Python add item to the tuple
Asked Answered
T

10

238

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.

Trichoid answered 24/5, 2013 at 8:4 Comment(0)
A
424

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

a = ('2',)
b = 'z'
new = a + (b,)
Aeroembolism answered 24/5, 2013 at 8:5 Comment(6)
Why you need this commaGoogolplex
@SIslam Without the comma, it will just be interpreted as brackets usually used to get around the order of precedence: (a+b)*cSapheaded
yeah, but you can do new = a + b instead of new = a + (b,). AFAICT, works the same in python3 and python2.7.Jacobinism
@Jacobinism depends what b is thoughAeroembolism
Or shortly a += ('z',), as mentioned in bellow answerClanton
It's the comma that creates the tuple, not the parentheses. (The only tuple that doesn't require a comma is the empty tuple). The parentheses here ensure that we define a sum of tuples, rather than a tuple consisting of a sum like a + b,. (Basically, the comma "operator" has extremely low precedence.)Feminacy
A
102

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

a = ('2',)
b = 'z'
new = (*a, b)
Annis answered 28/8, 2016 at 15:56 Comment(2)
I am trying it on Python 3.7.10, and it works with a = ('2'). That is without the additional comma.Rebirth
@Rebirth the comma makes it a tuple, without it it's just a string. Try a = ('23') and new becomes ('2', '3', 'z'). If you add the comma then you get ('23', 'z').Annis
O
45

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.

Orit answered 24/5, 2013 at 8:22 Comment(4)
This will be twice as slow as just adding two tuplesAbstention
However if you note to OP to convert to list at the beginning, append items, and then at the very end convert to tuple then this is the best solution +1Abstention
two items including the first itemin list. but you are right, i should better add a longer=list example, see my editOrit
i kinda like this answer the best... while it is probably a bit more expensive, it looks very clean.Iq
R
21

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')
Roundlet answered 2/7, 2014 at 15:25 Comment(0)
A
12
>>> 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')
Abstention answered 24/5, 2013 at 8:5 Comment(0)
P
9

#1 form

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

#2 form

a = ('x', 'y')
b = a + tuple('b')
print(b)
Pipistrelle answered 18/8, 2017 at 16:27 Comment(1)
second option does not work. TypeError: 'int' object is not iterableNat
A
4

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)
Arnuad answered 15/9, 2022 at 2:41 Comment(2)
Note: if 'c' is an int, you might as well add the comma (or use str(c))Arnuad
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Lockup
T
3

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)
Tried answered 7/2, 2020 at 5:20 Comment(0)
I
-1

my favorite:

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

Yes, I know it is expensive, but it sure looks cool :)

Iq answered 17/12, 2022 at 14:50 Comment(0)
K
-2
tup = (23, 2, 4, 5, 6, 8)
n_tup = tuple(map(lambda x: x+3, tup))
print(n_tup)
Kraigkrait answered 27/10, 2022 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.