当需要根据既有列表创建全新的列表时,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])
示例:
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
结果:
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
倘若直接将一个列表赋给到另一个列表,就不能得到两个列表。
示例:
my_foods = ['pizza', 'falafel', 'carrot cake']
#这行不通
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
结果:
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
这种语法实际上是让Python将新变量friend_foods 关联到包含在my_foods 中的列表,因此这两个变量都指向同一个列表。鉴于此,当我们将'cannoli' 添加到my_foods 中时,它也将出现在friend_foods 中;同样,虽然'icecream' 好像只被加入到了friend_foods 中,但它也将出现在这两个列表中。