[Tutor] In-place expansion of list members... possible?

Eric Brunson brunson at brunson.com
Wed Nov 7 21:28:02 CET 2007


Marc Tompkins wrote:
> This question has probably been asked and answered many times, but I 
> can't figure out how to word my question to get relevant results from 
> Google.  So I thought I'd try some human beings, eh?
>
> I'm working with delimited files (ANSI X12 EDI nonsense, to be 
> precise.)  First I load the records to a list:
>         tmpSegs = inString.split(self.SegTerm)
>
> Now, I want to replace each string in that list with a string:
>
>         for seg in tmpSegs:       # 'seg' is short for 'segment'
>             seg = seg.split(self.ElemSep)

A list is an array of pointers to objects, what you've done here is 
create a new name referencing an item in the list, then making that new 
name point to something different.

Try this (untested code):

for index in xrange(0, len(tmpSegs)):
    tmpSegs[index] = tmpSegs[index].split(self.ElemSep)


This will iterate through the list and set each reference in the list to 
point to your new object.

Hope that helps,
e.


>
> It doesn't work.  If I check the contents of tmpSegs, it's still a 
> list of strings - not a list of lists.  So I do this instead:
>         tmpSegs2 = []
>         for seg in tmpSegs:
>             tmpSegs2.append(seg.split(self.sElemSep))
>         del tmpSegs
>
> This works.  And, for the size of files that I'm likely to run into, 
> creating the extra list and burning the old one is probably not going 
> to swamp the machine - but it feels clumsy to me, like if I just knew 
> the secret I could be much more elegant about it.  I don't want the 
> next guy who reads my code to scratch his head and say 'What was he 
> thinking?' - especially if it's me in a year's time!
>
> What puzzles me most is that I can replace 'seg' with just about 
> anything else -
>         for seg in tmpSegs:
>             seg = seg.strip()
> or
>         for seg in tmpSegs:
>             seg = 'bananas'
> or
>         for seg in tmpSegs:
>             seg = seg + ' bananas'
> and it works.  So why can't I replace it with its own split?
>
> It's not a burning question - development continues - but I'm really 
> curious.
>
> Thanks!
> -- 
> www.fsrtechnologies.com <http://www.fsrtechnologies.com>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list