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.创建新列表:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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']