为什么Python中有单独的元组和列表数据类型
提供单独的元组和列表数据类型是因为它们有不同的角色。元组是不可变的,而列表是可变的。这意味着列表可以被修改,而元组不可以被修改。
元组和列表都是序列。元组和列表的区别在于,元组是不可变的,不像列表可以被修改,而且元组使用圆括号,列表使用方括号。
让我们看一下如何创建列表和元组。
创建一个基本的元组
示例
首先我们创建一个包含整数元素的基本元组,然后再讨论元组中的元组。
# Creating a Tuple
mytuple = (20, 40, 60, 80, 100)
# Displaying the Tuple
print("Tuple = ",mytuple)
# Length of the Tuple
print("Tuple Length= ",len(mytuple))
输出
Tuple = (20, 40, 60, 80, 100)
Tuple Length= 5
创建一个Python列表
示例
我们将创建一个包含10个整数元素的列表并显示它。元素用方括号括起来。同时,我们还显示了列表的长度以及如何使用方括号访问特定元素-
# Create a list with integer elements
mylist = [25, 40, 55, 60, 75, 90, 105, 130, 155, 180];
# Display the list
print("List = ",mylist)
# Display the length of the list
print("Length of the List = ",len(mylist))
# Fetch 1st element
print("1st element = ",mylist[0])
# Fetch last element
print("Last element = ",mylist[-1])
输出
List = [25, 40, 55, 60, 75, 90, 105, 130, 155, 180]
Length of the List = 10
1st element = 25
Last element = 180
我们可以更新元组的值吗
示例
如上所述,元组是不可变的,不能被更新。但是,我们可以将元组转换为列表,然后再更新它。
让我们来看一个示例 –
myTuple = ("John", "Tom", "Chris")
print("Initial Tuple = ",myTuple)
# Convert the tuple to list
myList = list(myTuple)
# Changing the 1st index value from Tom to Tim
myList[1] = "Tim"
print("Updated List = ",myList)
# Convert the list back to tuple
myTuple = tuple(myList)
print("Tuple (after update) = ",myTuple)
输出
Initial Tuple = ('John', 'Tom', 'Chris')
Updated List = ['John', 'Tim', 'Chris']
Tuple (after update) = ('John', 'Tim', 'Chris')