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

更新于: 2022 年 9 月 16 日

133 次浏览

开始你的 职业

完成课程获得认证

立即开始
广告
© . All rights reserved.