将一个列表的值复制到另一个列表,如将my_foods拷贝到friend_foods,需要使用如下的程序,才可分别对这两个列表的值进行修改,两个列表的值可以不同
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] #也可使用 friend_foods = my_foods.copy()
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("
My 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']
如果使用
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("
My 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']
两个列表的值始终相同
参考4.4.3节