Python—The difference between a list and a tuple

1. Create

Use [] for the creation of the list, and () for the shipbuilding of the tuple

When there is only one element in the tuple, the creation of the tuple needs to add a comma ",", the comma is the key to the tuple

>>>temp1 = (1)
>>>temp2 = (1,)

>>>print( type(temp1) )
<class 'int'>

>>>print( type(temp2) )
<class 'tuple'>

Create empty list and empty array

list1=[]
tuple1=()

2. Access

Access to tuples is similar to arrays, and both can be accessed using slices

3. Update

The list can be updated, using functions such as append, extend, insert, or using slices

But the tuple is not updatable, you can only create a new tuple and assign it to the original variable name

>>> temp=(1,2,3,4,5,6)
>>> temp=temp[:2]+("字符串",)+temp[2:]
>>> temp
(1, 2, '字符串', 3, 4, 5, 6)

Tuples can use the connecting character "+"

4. Delete

Tuples are static, and their internal elements cannot be updated, nor can one or some of them be deleted. But you can delete the entire tuple

>>> temp=(1,2,3,4,5,6)
>>> del temp
>>> temp
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    temp
NameError: name 'temp' is not defined

Note: The comparison, logic, concatenation and repeat operators of lists are also applicable in tuples.

Guess you like

Origin blog.csdn.net/weixin_43217427/article/details/107407309