Copy of Python list

1. Assign value directly by name:

my_habit = ['game', 'running']
friend_habit = my_habit
my_habit.append('swimming')
friend_habit.append('pingpang')
print(my_habit)
print(friend_habit)

The output is:

['game', 'running', 'swimming', 'pingpang']
['game', 'running', 'swimming', 'pingpang']

Here will be my_habitassigned friend_habitinstead to store a copy of my_habit friend_habit, this syntax is designed to let the new Python variables friend_habitassociated to be included in my_habitthe list, so these two variables are the same list.

2. Create a new list:

'''
遇到问题没人解答?小编创建了一个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)

The output is:

['game', 'running', 'swimming']
['game', 'running', 'pingpang']

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/109292374