问题: 解释 Python 中列表和元组的主要区别,并举例说明这些区别。
解决方案: 在 Python 中,列表和元组都用于存储项目集合,但它们有一些重要的区别:
# Mutability:
# Lists are mutable
my_list = [1, 2, 3]
my_list[0] = 4
# Now my_list is [4, 2, 3]
# Tuples are immutable
my_tuple = (1, 2, 3)
my_tuple[0] = 4 # This will raise an error
# Syntax:
# List: Lists are defined using square brackets [].
# Tuple: Tuples are defined using parentheses ().
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
# Performance:
# List of student scores (mutable)
student_scores = [90, 85, 78, 92]
# Coordinates of a point (immutable)
point_coordinates = (3, 4)
# Methods:
my_list.append(5) # Add an element to a list
my_tuple.count(2) # Count occurrences of an element in a tuple
