简体   繁体   中英

Adding a tuple to a tuple of tuples

I know, this is easy...

I have the following tuple:

((1,2), (3,4), (5,6))

I need to add (7,8) to this so the result:

((7,8), (1,2), (3,4), (5,6))

Thanks

Tuples are immutable, you will need to create a new tuple.

mytuple = ((7,8),) + mytuple

((7,8),) is a tuple which contains exactly one tuple. The additional comma is needed to distinguish a tuple with one element from an expression.

Demo:

>>> a = (3)
>>> type(a)
<class 'int'>
>>> a = (3,)
>>> type(a)
<class 'tuple'>

For ((7,8),) :

>>> a = ((7,8))
>>> a
(7, 8)
>>> type(a)
<class 'tuple'>
>>> type(a[0])
<class 'int'>
>>> a = ((7,8),)
>>> a
((7, 8),)
>>> type(a)
<class 'tuple'>
>>> type(a[0])
<class 'tuple'>

You could also to use append() method :

yourTuple.append(valueToAppend)

http://www.tutorialspoint.com/python/tuple_append.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM