Nested list problem - please...

Discussion in 'Python' started by Martin Hvidberg, Apr 17, 2010.

  1. Dear list

    I have this code, it builds up a data structure of nested lists, and filling data in them.
    My problem is that it seems that one of the lists SA[1] is not a list of unique instances but rather individual links to the same variable.
    In the example below I assign 'X' to what I intended to be the first Compounds Name. But rather the 'X' goes into all the Compounds Name.
    I thought that the [:] in SAdata.extend([CP[:]]) would ensure copies rather than links to.
    What is going wrong?

    I include sample code, and I include the output it produces, and I manually inserted some line breaks and some indents, for readability.

    :) Martin

    --- Code Start ---
    LV = list() # LV for Lable Value pair
    LV.extend(['lable','0'])

    CP = list() # CP for ComPund
    for i in range(0,5):
    CP.extend([LV[:]]) # incl. 5 _copies_ of LV
    CP[0][0] = 'Compound name'
    CP[1][0] = 'Tgt'
    CP[2][0] = 'Q1'
    CP[3][0] = 'Q2'
    CP[4][0] = 'Q3'

    SA = list() # SA for SAmple
    SAheader = list()
    for i in range(0,3):
    SAheader.extend([LV[:]])
    SAheader[0][0] = 'fileinfo.txt'
    SAheader[1][0] = 'Data file'
    SAheader[2][0] = 'Sample name'
    SA.extend([SAheader])
    SAdata = list()
    for i in range(0,2):
    SAdata.extend([CP[:]])
    SA.extend([SAdata])

    print SA
    SA[1][0][0][1] = 'X'
    print SA
    --- Code End ---


    [
    [
    ['fileinfo.txt', '0'],
    ['Data file', '0'],
    ['Sample name', '0']
    ],
    [
    [
    ['Compound name', 'X'],
    ['Tgt', '0'],
    ['Q1', '0'],
    ['Q2', '0'],
    ['Q3', '0']
    ],
    [
    ['Compound name', 'X'],
    ['Tgt', '0'],
    ['Q1', '0'],
    ['Q2', '0'],
    ['Q3', '0']
    ]
    ]
    ]
    Martin Hvidberg, Apr 17, 2010
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    4
    Views:
    491
    Chris Uppal
    May 5, 2005
  2. KK
    Replies:
    2
    Views:
    518
    Big Brian
    Oct 14, 2003
  3. MuZZy
    Replies:
    7
    Views:
    1,717
    Mike Hewson
    Jan 7, 2005
  4. Replies:
    2
    Views:
    492
    Gerard Flanagan
    Mar 22, 2006
  5. Replies:
    3
    Views:
    457
    Victor Bazarov
    Dec 7, 2007
Loading...

Share This Page