Bản sao gán danh sách Python

Bạn không thể sao chép một danh sách đơn giản bằng cách gõ list2 = list1, bởi vì. list2 sẽ chỉ là tham chiếu đến list1 và những thay đổi được thực hiện trong list1 cũng sẽ tự động được thực hiện trong list2

Có nhiều cách để tạo một bản sao, một cách là sử dụng phương thức Danh sách tích hợp sẵn

#Defining a list
list = [a,b,c]

#Copying list
list_new = list.copy[]

print ["This is the new list: " + str[list_new]]

list_new.append[d]

print ["The new list after adding a new element: " + str[list_new]]
print ["The old list after adding a new element" + str[list]]
2

Ví dụ

Tạo một bản sao của danh sách bằng phương pháp

#Defining a list
list = [a,b,c]

#Copying list
list_new = list.copy[]

print ["This is the new list: " + str[list_new]]

list_new.append[d]

print ["The new list after adding a new element: " + str[list_new]]
print ["The old list after adding a new element" + str[list]]
2

thislist = ["apple", "banana", "cherry"]
mylist = thislist. copy[]
print[mylist]

Tự mình thử »

Một cách khác để tạo bản sao là sử dụng phương pháp tích hợp sẵn

#Defining a list
list = [a,b,c]

#Copying list
list_new = list.copy[]

print ["This is the new list: " + str[list_new]]

list_new.append[d]

print ["The new list after adding a new element: " + str[list_new]]
print ["The old list after adding a new element" + str[list]]
4

Ví dụ

Tạo một bản sao của danh sách bằng phương pháp

#Defining a list
list = [a,b,c]

#Copying list
list_new = list.copy[]

print ["This is the new list: " + str[list_new]]

list_new.append[d]

print ["The new list after adding a new element: " + str[list_new]]
print ["The old list after adding a new element" + str[list]]
4

thislist = ["apple", "banana", "cherry"]
mylist = list[thislist]
print[mylist]

Chủ Đề