1.直接按名字赋值:
my_habit = ['game', 'running'] friend_habit = my_habit my_habit.append('swimming') friend_habit.append('pingpang') print(my_habit) print(friend_habit)
输出结果为:
['game', 'running', 'swimming', 'pingpang'] ['game', 'running', 'swimming', 'pingpang']
这里将my_habit赋给friend_habit,而不是将my_habit的副本存储到friend_habit,这种语法其实是让Python将新变量friend_habit关联到包含在my_habit中的列表,因此这两个变量都是同一个列表。
2.创建新列表:
my_habit = ['game', 'running'] friend_habit = my_habit[:] my_habit.append('swimming') friend_habit.append('pingpang') print(my_habit) print(friend_habit)
输出结果为:
['game', 'running', 'swimming'] ['game', 'running', 'pingpang']