To copy a list, you can use list(a) or a[:] . In both cases, a new object is created.
However, these two methods have limitations on collections of mutable objects, since internal objects keep their links intact:
>>> a = [[1,2],[3],[4]] >>> b = a[:] >>> c = list(a) >>> c[0].append(9) >>> a [[1, 2, 9], [3], [4]] >>> c [[1, 2, 9], [3], [4]] >>> b [[1, 2, 9], [3], [4]] >>>
If you need a full copy of your objects, you need copy.deepcopy
>>> from copy import deepcopy >>> a = [[1,2],[3],[4]] >>> b = a[:] >>> c = deepcopy(a) >>> c[0].append(9) >>> a [[1, 2], [3], [4]] >>> b [[1, 2], [3], [4]] >>> c [[1, 2, 9], [3], [4]] >>>
joaquin Jan 05 2018-12-12T00: 00Z
source share