内置函数 tuple() 用于在 Python 中创建元组。元组是一个包含多个元素的单一变量。元组中的元素是不可变的,这意味着不能修改它们。
tuple(iterable) #where iterable may be list, range, dict etc
接受单个参数。元组元素有序、不可更改,并允许重复值。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 可迭代对象 | 一个可迭代对象(列表、范围等)或一个迭代器对象 | 可选 |
如果未将可迭代对象传递给 tuple(),则该函数将创建一个空元组并返回 TypeError。
| 输入 | 返回值 |
|---|---|
| 如果可迭代 | 元组 |
tuple1 = tuple()
print('tuple1 =', tuple1)
# creating a tuple from a list
tuple2 = tuple([2, 3, 5])
print('tuple2 =', tuple2)
# creating a tuple from a string
tuple1 = tuple('Python')
print('tuple1 =',tuple1)
# creating a tuple from a dictionary
tuple1 = tuple({2: 'one', 4: 'two'})
print('tuple1 =',tuple1)
输出
tuple1 = ()
tuple2 = (2, 3, 5)
tuple1 = ('P', 'y', 't', 'h', 'o', 'n')
tuple1 = (2, 4)
# Error when a non-iterable is passed
tuple1 = tuple(1)
print(tuple1)
输出
Traceback (most recent call last):
File "/home/eaf759787ade3942e8b9b436d6c60ab3.py", line 5, in
tuple1=tuple(1)
TypeError: 'int' object is not iterable