copying a list
Kalle Svensson
kalle at gnupung.net
Tue Aug 8 12:29:09 EDT 2000
On Tue, 8 Aug 2000, lance wrote:
> is there an easy way to get a copy of a list instead of a reference to that
> list?
The easiest way is by using the slice:
>>> x = [1, 2]
>>> y = x[:]
>>> y[1] = 3
>>> x, y
([1, 2], [1, 3])
If you use nested lists this might not be good enough:
>>> x = [[1, 2], [3, 4]]
>>> y = x[:]
>>> y[1][1] = 5
>>> x, y
([[1, 2], [3, 5]], [[1, 2], [3, 5]])
^
In this case, use deepcopy from the copy module (in the standard library):
>>> x = [[1, 2], [3, 4]]
>>> import copy
>>> y = copy.deepcopy(x)
>>> y[1][1] = 5
>>> x, y
([[1, 2], [3, 4]], [[1, 2], [3, 5]])
HTH,
Kalle Svensson
--
Email: kalle at gnupung.net | You can tune a filesystem, but you
Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8)
More information about the Python-list
mailing list