I just put it in the sauce below, and when list1 changes, list2 changes, too For me, list2 should be [1,2,3] continuously.
I don't want to turn the door around and copy each and every one of them Please let me know if there's a Python function
list1 = [1,2,3]
list2 = list1
list1.append(4)
There are many ways to copy a list.
list2 = list1[:]
list2 = list(list1)
import copy
list2 = copy.copy(list1)
import copy
list2 = copy.deepcopy(list1)
There is a slight difference in each method. I'll let you know by example
import copy
list1 = ["list1"]
list2 = ["list2"]
list1.append(list2)
print "Original list1:", list1
result1 = list1[:]
result2 = list(list1)
result3 = copy.copy(list1)
result4 = copy.deepcopy(list1)
print "\nResult of pasting: "
print "list1[:]\t\t\t\t", result1
print "list(list1)\t\t\t\t", result2
print "copy.copy(list1)\t\t", result3
print "copy.deepcopy(list1)\t", result4
print "When I changed \nlist1"
list1.append("list1.append")
list2.append("list2.append")
print "changed list1\t\t\t\t", list1
print "list1[:]\t\t\t\t", result1
print "list(list1)\t\t\t\t", result2
print "copy.copy(list1)\t\t", result3
print "copy.deepcopy(list1)\t", result4
Results are
Original list1: ['list1', ['list2']
Result of pasting:
list1[:] ['list1', ['list2']]
list(list1) ['list1', ['list2']]
copy.copy(list1) ['list1', ['list2']]
copy.deepcopy(list1) ['list1', ['list2']]
When I changed the list 1,
Changed list1 ["list1", ["list2", "list2.append", "list1.append"]
list1[:] ['list1', ['list2', 'list2.append']]
list(list1) ['list1', ['list2', 'list2.append']]
copy.copy(list1) ['list1', ['list2', 'list2.append']]
copy.deepcopy(list1) ['list1', ['list2']]
I hope it helps you
© 2024 OneMinuteCode. All rights reserved.