How I copy a list in python, if I want the orginal list has no effect on the copy one?

Viewed 46

I have a list with some set in it, the list looks like this:

[{1,2},{2,3},{0,1}]

How can I copy it to a new one, and they will not have any effect with each other?

I have used these functions, but no way to change them.

a = [{1,2}, {0}, {0}, set()]
b = a[:]
b = copy.copy(a)
2 Answers
import copy
 
a=[{1,2},{2,3},{0,1}]
b = copy.deepcopy(a) 

If you know your list has a fixed structure and only contains a set of int values, it might be more efficient to use set.copy().

On my machine, it appears to be about 25x faster overall than copy.deepcopy.

from copy import deepcopy
from timeit import timeit

S = [{1, 2}, {2, 3}, {0, 1}]

print('set.copy:      ', timeit('[s.copy() for s in S]', globals=globals()))
print('copy.deepcopy: ', timeit('deepcopy(S)', globals=globals()))

When running this on Mac M1:

set.copy:       0.24300479097291827
copy.deepcopy:  6.54383279196918
Related