Two ways to add elements to python tuple tuple

Two ways to add elements to python tuple tuple

Method 1 : You can use python’s built-in __add__() method. When using this method to add elements to a python tuple, you need to use the tuple object to call, and then pass the element to be added with the data type of the tuple. This method does not need to modify the calling object, but returns a new tuple. See the example code below for details.

Method 2 : Convert the python tuple object into a list first, then use the append() method to add elements, and then use the tuple() function to convert it into a tuple type.

python tuple tuple add element example code

#__add__()方法
>>> a = (1,)
>>> a.__add__((2,3))
(1, 2, 3)
>>> a
(1,)
#list append()方法
>>> a = list(a)
>>> a
[1]
>>> a.append(8)
>>> a
[1, 8]
>>> a = tuple(a)
>>> a
(1, 8)

Original: Two ways to add elements to a python tuple tuple

Guess you like

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