append to a sublist - please help

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Helmut Jarausch

    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
  • Arnaud Delobelle

    #2
    Re: append to a sublist - please help

    On Apr 6, 5:16 pm, Helmut Jarausch <jarau...@skyne t.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:

    Contents: Programming FAQ- General Questions- Is there a source code level debugger with breakpoints, single-stepping, etc.?, Are there tools to help find bugs or perform static analysis?, How can ...


    HTH

    --
    Arnaud

    Comment

    • Lie

      #3
      Re: append to a sublist - please help

      On Apr 6, 11:16 pm, Helmut Jarausch <jarau...@skyne t.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

      Comment

      Working...