The Python Oracle

Python add item to the tuple

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops

--

Chapters
00:00 Question
00:29 Accepted answer (Score 407)
00:43 Answer 2 (Score 96)
01:01 Answer 3 (Score 44)
01:51 Answer 4 (Score 19)
02:15 Thank you

--

Full question
https://stackoverflow.com/questions/1673...

Answer 1 links:
[PEP 448]: https://www.python.org/dev/peps/pep-0448/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #tuples

#avk47



ACCEPTED ANSWER

Score 427


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

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



ANSWER 2

Score 47


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.




ANSWER 3

Score 22


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')



ANSWER 4

Score 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')