470,631 Members | 1,622 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,631 developers. It's quick & easy.

append to a sublist - please help

Hi,

I must be blind but I don't see what's going wrong
with

G=[[]]*2

G[0].append('A')
G[1].append('B')
print G[0]

gives

['A', 'B']

as well as
print G[1]

I was expecting
['A']
and
['B']
respectively.

Many thanks for enlightening me,
Helmut.

--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
Apr 6 '08 #1
2 3940
On Apr 6, 5:16*pm, Helmut Jarausch <jarau...@skynet.bewrote:
Hi,

I must be blind but I don't see what's going wrong
with

G=[[]]*2

G[0].append('A')
G[1].append('B')
print G[0]

gives

['A', 'B']

as well as
print G[1]

I was expecting
['A']
and
['B']
respectively.

Many thanks for enlightening me,
Helmut.

--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
This is in the top two FAQ, here is the relevant section:

http://www.python.org/doc/faq/progra...mensional-list

HTH

--
Arnaud

Apr 6 '08 #2
Lie
On Apr 6, 11:16 pm, Helmut Jarausch <jarau...@skynet.bewrote:
Hi,

I must be blind but I don't see what's going wrong
with

The reason is:
G=[[]]*2
is doing a "shallow copy" of the blank list. The corrected code is
either:

G = [[] for _ in xrange(2)]

or

G = [[], []]

btw, this is a very frequently asked question
Apr 6 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Bill | last post: by
1 post views Thread by Bernard A. | last post: by
4 posts views Thread by yaffa | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.