
提供单独的元组和列表数据类型,因为两者具有不同的角色。元组是不可变的,而列表是可变的。这意味着列表可以修改,而元组则不能。
元组是序列,就像列表一样。元组和列表之间的区别在于,与列表不同,元组不能更改,并且元组使用括号,而列表使用方括号。
让我们看看如何创建列表和元组。
创建一个基本元组
示例
让我们首先创建一个包含整数元素的基本元组,然后转向元组内的元组
立即学习“Python免费学习笔记(深入)”;
所谓数组,就是相同数据类型的元素按一定顺序排列的集合,就是把有限个类型相同的变量用一个名字命名,然后用编号区分他们的变量的集合,这个名字称为数组名,编号称为下标。组成数组的各个变量称为数组的分量,也称为数组的元素,有时也称为下标变量。数组是在程序设计中,为了处理方便, 把具有相同类型的若干变量按有序的形式组织起来的一种形式。这些按序排列的同类数据元素的集合称为数组。 数组应用&二维数组目录 1. 数组的简单应用2. 数组排序3. 数组查找4. 数组的使用思想5. 查表法6. 二维数组7. 数组综合
# 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')










