Using built-in method list() to copy list. Another way to copy a list in Python is to use the built-in method list(). It also creates a shallow copy which means any time a modification is made in the new list, it will not show on the old list.
In Python, a shallow copy can be created using copy. copy() function. A shallow copy solves our problem of copying a list in a way it does not depend on the original list. As you can see, changing the first element in the original list did not change the copied list.
For a more general solution that works regardless of the number of dimensions, use copy.deepcopy()
:
import copy
b = copy.deepcopy(a)
b = [x[:] for x in a]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With