玖叶教程网

前端编程开发入门

一文掌握Python List 和 Tuple 之间的区别

列表和元组都是 Python 中的数据结构,但它们有一些关键区别:

1. 语法:

列表:使用方括号 [] 创建列表。

元组:元组是使用括号创建 () 的。

# List creation using square brackets
my_list = [1, 2, 3, 4, 5]
print("List:", my_list)


# Tuple creation using parentheses
my_tuple = (1, 2, 3, 4, 5)
print("Tuple:", my_tuple)

2.可变性:

列表:列表是可变的,这意味着您可以在创建列表后修改、添加或删除元素。可以使用 、 extend()insert()remove()pop()append() 方法来修改列表。

元组:元组是不可变的。创建元组后,无法更改其元素。不能添加、删除或修改元组中的元素。

# List is mutable - modifying elements
my_list = [1, 2, 3]
my_list[0] = 10
print("Modified List:", my_list)


# Tuple is immutable - attempting to modify will raise an error
my_tuple = (1, 2, 3)
# The following line will result in an error
# my_tuple[0] = 10

3.记忆:

列表:列表通常比元组占用更多内存,因为列表是可变的。列表可以动态增长或缩小,这种灵活性会带来略高的内存开销。

元组:与列表相比,元组的内存效率更高。创建元组后,其大小将保持不变。

# Lists are more memory-intensive
import sys
my_list = [1, 2, 3, 4, 5]
print("Memory used by list:", sys.getsizeof(my_list))

#O/t- Memory used by list: 104


# Tuples are more memory-efficient
my_tuple = (1, 2, 3, 4, 5)
print("Memory used by tuple:", sys.getsizeof(my_tuple))

#O/t- Memory used by tuple: 80

4.可用性:

列表:当您有可能需要修改的项集合,并且需要动态数据结构时,请使用列表。

元组:如果要创建应在整个程序中保持不变的项集合,并且希望确保数据完整性,请使用元组。


# Use lists for dynamic data structures
dynamic_list = [1, 2, 3]
dynamic_list.append(4)
print("Dynamic List:", dynamic_list)

# Use tuples for constant data structures
constant_tuple = (1, 2, 3)
# The following line will result in an error since tuples are immutable
# constant_tuple.append(4)

但是,列表解包和元组解包都可用。

元组解包:Python 中的元组解包允许您将元组的各个元素分配给单独的变量。此功能使使用元组变得方便,尤其是当您有返回元组的函数或想要从可迭代对象中提取值时。

a,b,c = (1,2,3)
print(a,b,c)

#Output
1 2 3

a,b,*others = (1,2,3,4)
print(a,b)
print(others)
#Output
1 2
[3,4]

列表解包:允许您提取列表的元素并将它们分配给各个变量。当您有一个包含多个元素的列表,并且想要将每个元素分配给一行中的单独变量时,这特别有用。

# List with multiple elements
my_list = [1, 2, 3]

# Unpacking the list into individual variables
a, b, c = my_list

# Printing the unpacked values
print("a:", a)
print("b:", b)
print("c:", c)


# List with more elements
another_list = [4, 5, 6, 7, 8]

# Unpacking into individual variables
x, y, *rest = another_list

# Printing the unpacked values
print("x:", x)
print("y:", y)
print("Rest of the list:", rest)

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言