Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying nested lists in Python

People also ask

Can you copy lists in Python?

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.

How do I copy a list to another list in Python without a reference?

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]