为什么Python中有分别的元组和列表数据类型?
提供单独的元组和列表数据类型,因为两者具有不同的角色。元组是不可变的,而列表是可变的。这意味着列表可以修改,而元组则不能。
元组是序列,就像列表一样。元组和列表之间的区别在于,与列表不同,元组不能更改,并且元组使用括号,而列表使用方括号。
让我们看看如何创建列表和元组。
创建一个基本元组
示例
让我们首先创建一个包含整数元素的基本元组,然后转向元组内的元组
立即学习“Python免费学习笔记(深入)”;
# Creating a Tuplemytuple = (20, 40, 60, 80, 100)# Displaying the Tupleprint("Tuple = ",mytuple)# Length of the Tupleprint("Tuple Length= ",len(mytuple))
输出
Tuple = (20, 40, 60, 80, 100)Tuple Length= 5
创建 Python 列表
示例
我们将创建一个包含 10 个整数元素的列表并显示它。元素用方括号括起来。这样,我们还显示了列表的长度以及如何使用方括号访问特定元素 -
# Create a list with integer elementsmylist = [25, 40, 55, 60, 75, 90, 105, 130, 155, 180];# Display the listprint("List = ",mylist)# Display the length of the listprint("Length of the List = ",len(mylist))# Fetch 1st elementprint("1st element = ",mylist[0])# Fetch last elementprint("Last element = ",mylist[-1])
输出
List = [25, 40, 55, 60, 75, 90, 105, 130, 155, 180]Length of the List = 101st element = 25Last element = 180
我们可以更新元组值吗?
示例
如上所述,元组是不可变的并且无法更新。但是,我们可以将 Tuple 转换为 List,然后更新它。
让我们看一个例子 -
myTuple = ("John", "Tom", "Chris")print("Initial Tuple = ",myTuple)# Convert the tuple to listmyList = list(myTuple)# Changing the 1st index value from Tom to TimmyList[1] = "Tim"print("Updated List = ",myList)# Convert the list back to tuplemyTuple = tuple(myList)print("Tuple (after update) = ",myTuple)
输出
Initial Tuple = ('John', 'Tom', 'Chris')Updated List = ['John', 'Tim', 'Chris']Tuple (after update) = ('John', 'Tim', 'Chris')