Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Nested list problem - please...

Thread Tools

Nested list problem - please...

Martin Hvidberg
Posts: n/a
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.


--- Code Start ---
LV = list() # LV for Lable Value pair

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[0][0] = 'fileinfo.txt'
SAheader[1][0] = 'Data file'
SAheader[2][0] = 'Sample name'
SAdata = list()
for i in range(0,2):

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']

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Nested friend class in nested template problem C++ 3 12-07-2007 03:02 PM
Is nested class automatically friend of class that it is nested in? C++ 5 09-25-2006 08:31 AM
Convert (sorted) list of dics to nested list ? Python 2 03-22-2006 09:34 PM
Nested Vector Nester Classes are Nested in my Brain Chad E. Dollins C++ 3 11-08-2005 04:46 AM
Nested iterators (well, not nested exactly...) Russ Perry Jr Java 2 08-20-2004 06:51 PM