Problem with a tuple - newbie ignorance

Remco Gerlich scarblac at pino.selwerd.nl
Tue Jan 16 02:32:57 EST 2001


Steven Citron-Pousty <steven.citron-pousty at yale.edu> wrote in comp.lang.python:
> Greetings all:
> So I am writing this program to parse text files. I am using a tuple to 
> store the field names and values (i.e. [['id =', 't =', 
> ...]['','',...]]. The program reads through all the files in the 
> directory. For each file it writes all the all the matches in teh 
> appropriate field.  I am having several problems, but the biggest right 
> now is:
> When the program goes to parse the next file it doesn't clear out the 
> contents from the last file. Here is how I thought it should work...
> <Header stuff>
> ifields = [[fields names list][list of just '','','']
> <FOR loop with all the file names from the directory>
> open file
> results = ifields
> <fill the results tuple>
> <print the results tuple>
> <go back to the top of the loop>
> 
> For some reason I thought that each time results gets sets to ifields it 
> should reset the contents of results. I have tried all sorts of other 
> workarounds, such as using "del results" just before I go back and 
> repeat the loop.
> What am I missing here?

These are not tuples, but lists. (you can't change tuples).

When you do 'results = ifields', both variables refer to the same list.

So when you add elements to results, ifields is also changed, since it is
the same list.

Similar to:
>>> a = [1]
>>> b = a
>>> b.append(2)
>>> a
[1, 2]

What you need is a *copy* of the original list. So do
results = ifields[:]
instead.

Also, if you have a structure
[[name1, name2, name3, name4], [value, value, value, value]],
that just screams for a dictionary
{ name1: value, name2: value, name3: value, name4: value }

-- 
Remco Gerlich



More information about the Python-list mailing list