Tuples in Python

1 Introduction

  • Python tuples are similar to lists, except that the elements of tuples cannot be modified
  • Use parentheses for tuples ( )and square brackets for lists [].
  • Tuple creation is very simple, just add elements in parentheses and separate them with commas.
  • The element types in the tuple need not be the same
    Insert picture description here

2. Create

2.1 Create a tuple

>>> tup1=()	# 创建空元组
>>> tup1 = ('Google', 'Runoob', 1997, 2000)
>>> tup2 = (1,)	# 不能写成(1)这样解释器会接受成一个int类型,必须在后面加个逗号
>>> tup3 = "a", "b", "c", "d"   #  不需要括号也可以
>>> type(tup3)
<class 'tuple'>

2.1 The tuple function creates a tuple

The role of the tuple function: iterable elements can be converted into tuples

>>> str01='abcdefg'
>>> tup01=tuple(str01)
>>> type(tup01)
<class 'tuple'>
>>> print(tup01)
('a', 'b', 'c', 'd', 'e', 'f', 'g')

3 Access, modify, delete (tuples)

3.1 Access the elements in the tuple

>>> tup01=tuple('abcdefg')
>>> tup01[0]	# 访问第一个元素
'a'
>>> tup01[0:4]	# 访问第一个到第四个元素
('a', 'b', 'c', 'd')

Modify tuple

Once a tuple is created, it cannot be changed, it can only be combined with other tuples to generate a new tuple object

tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
 
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
 
# 创建一个新的元组
tup3 = tup1 + tup2
print (tup3)

3.3 delete tuples

Use delkeywords to delete tuples

tup = ('Google', 'Runoob', 1997, 2000)
 
print (tup)
del tup
print ("删除后的元组 tup : ")
print (tup)

After the above instance tuple is deleted, the output variable will have abnormal information, and the output is as follows:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print (tup)
NameError: name 'tup' is not defined

4. Tuple operator

Like character strings, you can use + and * to perform operations between tuples. This means that they can be combined and copied, and a new tuple will be generated after the operation.

Python expression result description
only ((1, 2, 3)) 3 Count the number of elements
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) connection
(‘Hi!’,) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') copy
3 in (1, 2, 3) true Whether the element exists
for x in (1, 2, 3): print (x,) 1,2,3 Iteration

5. Tuple index, interception

tup = ('Google', 'Runoob', 'Taobao', 'Wiki', 'Weibo','Weixin')

Insert picture description here

>>> tup = ('Google', 'Runoob', 'Taobao', 'Wiki', 'Weibo','Weixin')
>>> tup[1] #索引从零开始,返回第二个元素
'Runoob'
>>> tup[-2]	# 反序索引从-1开始,返回倒数第二个元素
'Weibo'
>>> tup[1:]# 切片,从第二个开始切片,一直到最后一个元素
('Runoob', 'Taobao', 'Wiki', 'Weibo', 'Weixin')
>>> tup[1:4] # 切片,从第二个元素开始,一直到第五个元素(但是不包括第五个元素)
('Runoob', 'Taobao', 'Wiki')
>>>

Guess you like

Origin blog.csdn.net/qq_42418169/article/details/109555960