Kent Johnson wrote: > Marc Tompkins wrote: >> 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) >> >> 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. > > Creating a new list is fine, actually. You can do it more elegantly with > a list comprehension, and it's fine to assign to the same name, which > will implicitly delete the old list: > tmpSegs = [ seg.split(self.ElemSep) for seg in tmpSegs ] > > If you really want to replace elements in the same list you can use > enumerate to get indices: > > for i, seg in enumerate(tmpSegs): > tmpSegs[i] = seg.split(self.ElemSep) > > or use slice assignment: > tmpSegs[:] = [ seg.split(self.ElemSep) for seg in tmpSegs ]
Won't the slice assignment create a new list and then assign it to the old list (which the OP is trying to avoid)? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor