Two ways to merge python tuples into one

Two ways to merge python tuples into one

In python, there may be more than two ways to combine tuples into one. The two methods introduced here are what I think of at the moment of writing:

  • Method 1: Use python's built-in "+" operator to directly "add" several tuples that need to be merged together. Note that this method does not modify any tuple, and returns a new tuple;
  • Method 2: Use python's built-in __add__() method, that is, use a tuple object to use this method, and pass the tuples that need to be merged to this method as formal parameters. If you need to merge multiple tuples, you can use lists or tuples to pack these tuples, and then add them iteratively through a for loop.

Python tuple merge example code

#“+”的方法:
>>> (1,)+(2,)
(1, 2)
>>> a=(1,)
>>> b=(2,)
>>> a+b
(1, 2)
>>> a
(1,)
>>> b
(2,)
#__add__()方法
>>> lst = [(1,),(2,3),(5,6)]
>>> result = tuple()
>>> for i in lst:
...     result = result.__add__(i)
... 
>>> result
(1, 2, 3, 5, 6)

Original post: Two ways to combine python tuples into one

Guess you like

Origin blog.csdn.net/weixin_47378963/article/details/130334305