a=b change b a==b true??

bayer.justin at googlemail.com bayer.justin at googlemail.com
Mon Feb 26 09:08:03 EST 2007


If you want to copy lists, you do it by using the [:] operator. e.g.:

>>> a = [1,2]
>>> b = a[:]
>>> a
[1, 2]
>>> b
[1, 2]
>>> b[0] = 2
>>> a
[1, 2]
>>> b
[2, 2]

If you want to copy a list of lists, you can use a list comprehension
if you do not want to use the copy module:

>>> a = [[1,2],[3,4]]
>>> b = [i[:] for i in a]
>>> a
[[1, 2], [3, 4]]
>>> b
[[1, 2], [3, 4]]
>>> b[0][0] = "foo"
>>> a
[[1, 2], [3, 4]]
>>> b
[['foo', 2], [3, 4]]




More information about the Python-list mailing list