Python tuple() 函数用于创建元组,元组是有序和不可变(不可更改)元素的集合。此集合可以包含各种数据类型,例如数字、字符串,甚至其他元组。
元组类似于列表,但主要区别在于,一旦创建了元组,就无法修改其元素,即无法添加、删除或更改它们。
语法
以下是 Python tuple() 函数的语法 -
tuple(iterable)
参数
此函数接受任何可迭代对象,如列表、字符串、集合或其他元组作为参数。
返回值
此函数返回一个新的 Tuples 对象,其中包含给定可迭代对象的元素。
示例 1在下面的示例中,我们使用 tuple() 函数将列表 “[1, 2, 3]” 转换为元组 −
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print('The tuple object obtained is:',my_tuple)
输出
以下是上述代码的输出 -
The tuple object obtained is: (1, 2, 3)
示例 2
在这里,我们使用 tuple() 函数将字符串 “Python” 转换为其单个字符的元组 -
my_string = "Python"
char_tuple = tuple(my_string)
print('The tuple object obtained is:',char_tuple)
输出
上述代码的输出如下 -
The tuple object obtained is: ('P', 'y', 't', 'h', 'o', 'n')
示例 3
在这里,我们使用不带任何参数的 tuple() 函数,创建一个空元组 ((()) −
empty_tuple = tuple()
print('The tuple object obtained is:',empty_tuple)
输出
获得的结果如下所示 -
The tuple object obtained is: ()
示例 4
在这种情况下,我们将集合 “{4, 5, 6}” 的元素转换为元组 −
my_set = {4, 5, 6}
set_tuple = tuple(my_set)
print('The tuple object obtained is:',set_tuple)
输出
以下是上述代码的输出 -
The tuple object obtained is: (4, 5, 6)
示例 5
在此示例中,我们使用 tuple() 函数对嵌套列表 “[[1, 2], [3, 4]]” 创建具有嵌套元组的元组 -
nested_list = [[1, 2], [3, 4]]
nested_tuple = tuple(nested_list)
print('The tuple object obtained is:',nested_tuple)
输出
生成的结果如下 -
The tuple object obtained is: ([1, 2], [3, 4])