List behaviour

B

barberomarcelo

Maybe I'm missing something but the latter is not the behaviour I'm
expecting:
a = [[1,2,3,4], [5,6,7,8]]
b = a[:]
b [[1, 2, 3, 4], [5, 6, 7, 8]]
a == b True
a is b False
for i in range(len(b)):
.... for x in range(4):
.... b[x] = b[x] + 10
....
b [[11, 12, 13, 14], [15, 16, 17, 18]]
a [[11, 12, 13, 14], [15, 16, 17, 18]]



ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on
Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)]
on win32
Windows XP

Marcelo
 
D

Diez B. Roggisch

Maybe I'm missing something but the latter is not the behaviour I'm
expecting:
a = [[1,2,3,4], [5,6,7,8]]
b = a[:]
b [[1, 2, 3, 4], [5, 6, 7, 8]]
a == b True
a is b False
for i in range(len(b)):
... for x in range(4):
... b[x] = b[x] + 10
...
b [[11, 12, 13, 14], [15, 16, 17, 18]]
a [[11, 12, 13, 14], [15, 16, 17, 18]]


b = a[:]

does clone a, but doesn't make a deepcopy of its contents, which you are
manipulating!

So do
[GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
poWelcome to rlcompleter2 0.96
for nice experiences hit said:
import copy
a = [[10]]
b = copy.deepcopy(a)
b[0][0] = 20
a [[10]]
b [[20]]


HTH,

Diez
 
M

Mike Kent

When you did:
b = a[:]

b was then a copy of a, rather than just a reference to the same a.
But what does a contain? It contains two sublists -- that is, it
contains references to two sublists. So b, which is now a copy of a,
contains copies of the two references to the same two sublists.

What you need to do instead is:
b = copy.deepcopy(a)

to get you what you actually want.
 
H

Heiko Wundram

Am Mittwoch 17 Mai 2006 17:06 schrieb (e-mail address removed):
Maybe I'm missing something but the latter is not the behaviour I'm

expecting:
a = [[1,2,3,4], [5,6,7,8]]
b = a[:]
b

[[1, 2, 3, 4], [5, 6, 7, 8]]

False

Try an:

here, and you'll see, that [:] only creates a shallow copy. Thus, the lists in
the lists aren't copied, they are shared by the distinct lists a and b.

Hope this clears it up.

--- Heiko.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,297
Messages
2,571,527
Members
48,249
Latest member
reactnativeexpert

Latest Threads

Top