append to a sublist - please help

  • Thread starter Helmut Jarausch
  • Start date
H

Helmut Jarausch

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
 
A

Arnaud Delobelle

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/programming/#how-do-i-create-a-multidimensional-list

HTH
 
L

Lie

Hi,

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


The reason is:

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
 

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

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top