简体   繁体   中英

add a tuple to a tuple in Python

I have a tuple:

a = (1,2,3)

and I need to add a tuple at the end

b = (4,5)

The result should be:

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

Even if I wrap b in extra parents: a + (b), I get (1,2,3,4,5) which is not what I wanted.

When you do a + b you are simply concatenating both the tuples. Here, you want the entire tuple to be a part of another tuple. So, we wrap that inside another tuple.

a, b = (1, 2, 3), (4,5)
print a + (b,)  # (1, 2, 3, (4, 5))
>>> a = (1,2,3)
>>> b = (4,5)
>>> a + (b,)
(1, 2, 3, (4, 5))

tuple objects are immutable. The result you're getting is a result of the fact that the + (and += ) operator is overridden to allow "extending" tuples the same way as lists . So when you add two tuples, Python assumes that you want to concatenate their contents .

To add an entire tuple onto the end of another tuple, wrap the tuple to be added inside another tuple.

c = a + (b,) # Add a 1-tuple containing the tuple to be added.
print(c) # >>> (1, 2, 3, (4, 5))

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