# Python四种基本数据结构之二——元组的简单使用(Two of the four basic data structures in Python — simple use of tuples)-python

## Python四种基本数据结构之二——元组的简单使用(Two of the four basic data structures in Python — simple use of tuples)

### 元组（tuple）

• typle在定义时，tuple的元素就必须被确定下来。
``````In [58]: t = (2, 1)

In [59]: t
Out[59]: (2, 1)

# 定义空的tuple
In [60]: t = ()

In [61]: t
Out[61]: ()

# 定义只有一个元素的tuple
# 注意：定义时，是有逗号的，若没有的话，就是定义1这个数
In [62]: t = (1, )

In [63]: t
Out[63]: (1,)

# 若没有逗号，则得到的不是一个元组
In [91]: a = (1)

In [92]: type(a)
Out[92]: int
``````
• 若tuple中有list，那么说的不可变，就是指向这个元素的这个指向不可变，但是list元素本身是可变的
``````In [73]: a = [1, 2]

In [74]: b = [3, 4]

In [75]: c = ('A', a)

In [76]: c
Out[76]: ('A', [1, 2])

# tuple元素指向不能改变，所以报了异常
In [77]: c[0] = b
--------------------------------------------------------------------
TypeError                          Traceback (most recent call last)
<ipython-input-77-5b8a7e0cb452> in <module>()
----> 1 c[0] = b

TypeError: 'tuple' object does not support item assignment

--------------------------------------------------------------------
# tuple中的list元素的内容可以改变
In [78]: c[1][1] = 3

In [79]: c
Out[79]: ('A', [1, 3])
``````
————————

### 元组（tuple）

< strong > tuples are also ordered tables. The difference is that tuples cannot be changed once they are initialized. When they remain unchanged here, the direction of each element of a tuple will never change < / strong >.

• When a type is defined, the elements of a tuple must be determined.
``````In [58]: t = (2, 1)

In [59]: t
Out[59]: (2, 1)

# 定义空的tuple
In [60]: t = ()

In [61]: t
Out[61]: ()

# 定义只有一个元素的tuple
# 注意：定义时，是有逗号的，若没有的话，就是定义1这个数
In [62]: t = (1, )

In [63]: t
Out[63]: (1,)

# 若没有逗号，则得到的不是一个元组
In [91]: a = (1)

In [92]: type(a)
Out[92]: int
``````
• If there is a list in a tuple, the immutability means that the point to this element is immutable, but the list element itself is variable
``````In [73]: a = [1, 2]

In [74]: b = [3, 4]

In [75]: c = ('A', a)

In [76]: c
Out[76]: ('A', [1, 2])

# tuple元素指向不能改变，所以报了异常
In [77]: c[0] = b
--------------------------------------------------------------------
TypeError                          Traceback (most recent call last)
<ipython-input-77-5b8a7e0cb452> in <module>()
----> 1 c[0] = b

TypeError: 'tuple' object does not support item assignment

--------------------------------------------------------------------
# tuple中的list元素的内容可以改变
In [78]: c[1][1] = 3

In [79]: c
Out[79]: ('A', [1, 3])
``````