How do I copy the Python list?

Asked 1 years ago, Updated 1 years ago, 92 views

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)

list python copy clone

2022-09-22 10:36

1 Answers

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


2022-09-22 10:36

If you have any answers or tips

Popular Tags
python x 4647
android x 1593
java x 1494
javascript x 1427
c x 927
c++ x 878
ruby-on-rails x 696
php x 692
python3 x 685
html x 656

© 2024 OneMinuteCode. All rights reserved.