首页 > 文章列表 > 为什么Python中有分别的元组和列表数据类型?

为什么Python中有分别的元组和列表数据类型?

数据类型 列表 元组
353 2023-09-06

提供单独的元组和列表数据类型,因为两者具有不同的角色。元组是不可变的,而列表是可变的。这意味着列表可以修改,而元组则不能。

元组是序列,就像列表一样。元组和列表之间的区别在于,与列表不同,元组不能更改,并且元组使用括号,而列表使用方括号。

让我们看看如何创建列表和元组。

创建一个基本元组

示例

让我们首先创建一个包含整数元素的基本元组,然后转向元组内的元组

# 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

我们可以更新元组值吗?

示例

如上所述,元组是不可变的并且无法更新。但是,我们可以将 Tuple 转换为 List,然后更新它。

让我们看一个例子 -

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')