王洲洋
王洲洋

Reputation: 5

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

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)

Upvotes: 0

Views: 61

Answers (2)

Wizard.Ritvik
Wizard.Ritvik

Reputation: 11612

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

Upvotes: 3

Niraj Gautam
Niraj Gautam

Reputation: 167

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

Upvotes: 3

Related Questions