Original white series of 8 Pian
List data structure can be modified, and the tuple is a fixed length, the data structure can not be modified element value.
Tuple using parentheses () indicates, the list using square brackets []. Please note the difference.
grammar:
Tuple name = ( element 1 , element 2, .......)
Tuple easiest way to create some of the values are separated by commas, the tuple is automatically created;
Most of the time the tuple is enclosed by parentheses; null set may contain no parentheses to represent; contains only one value tuple must add a comma (,);
example
tup1 = 1,2,3tup2 = "Python","Java"# 创建元组tup3 = (1,2,3,4)# 创建空元组tup4 = ()# 只有一个元素的元组tup5 = (1,)# 不是元组,是一个整型数字tup6 = (1)print(tup1)print(tup2)print(tup3)print(tup4)print(tup5)print(tup6)print(type(tup6))
(1, 2, 3)
('Python', 'Java')
(1, 2, 3, 4)
()
(1,)
1
<class 'int'>
Python中的tuple()函数也可以创建元组,将任意序列或迭代器放在该函数内即可。
注意该函数只接受任意序列或迭代器, 比如不能是数字的组合
例子tuple(1,2,3)。在Python编程中,我们经常使用tuple() 把列表变成元组。
另外,我们还可以通过双层圆括号创建元组的元组。
# 使用tuple()函数创建元组tup2_tuple = tuple('Python')print(tup2_tuple)tup3_tuple = tuple(['Python','Java','C++'])print(tup3_tuple)# 构造元组的元组tup7 = (1, 2, 3, 4),('Python','Java')print('创建元组的元组:',tup7)# 使用tuple()函数创建元组的元组tup_tuple = ((1, 2, 3, 4),('Python','Java'))print('使用tuple函数创建元组:',tup_tuple)
('P', 'y', 't', 'h', 'o', 'n')
('Python', 'Java', 'C++')
创建元组的元组: ((1, 2, 3, 4), ('Python', 'Java'))
使用tuple函数创建元组: ((1, 2, 3, 4), ('Python', 'Java'))
我们还可以通过加号(+)把多个元组拼接在一起,形成更长的元组;
也可以使用乘号(*)复制多份同样的元组。
# 通过 + 生成更长的元组tup8 = (1, 2, 3, 4) + ('Python', 'Java', 5) + ('C++',)print('通过 + 生成更长的元组',tup8)# 通过 * 生成多份同样的元组tup9 = ('Python','Java') * 3print('通过 * 生成多份同样的元组', tup9)
By + generating a longer tuple (1, 2, 3, 4 , 'Python', 'Java', 5, 'C ++')
By * generating multiple copies of the same tuple ( 'Python', 'Java' , 'Python', 'Java', 'Python', 'Java')
Above excerpt from "zero-based Easy Python"