By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,002 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,002 IT Pros & Developers. It's quick & easy.

append to a sublist - please help

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
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.