list insertion question

Jun.Jin.act+group.python@gmail.com Jun.Jin.act at gmail.com
Tue Apr 17 04:04:36 CEST 2007


On Apr 17, 9:47 am, Michael Hoffman <cam.ac... at mh391.invalid> wrote:
> eight02645... at yahoo.com wrote:
> > hi
> > i have a list (after reading from a file), say
> > data = [ 'a','b','c','d','a','b','e','d']
>
> > I wanted to insert a word after every 'a', and before every 'd'. so i
> > use enumerate this list:
> > for num,item in enumerate(data):
> >     if "a" in item:
> >    data.insert(num+1,"aword")
> >     if "d" in item:
> >         data.insert(num-1,"dword") #this fails
> > but the above only inserts after 'a' but not before 'd'.  What am i
> > doing wrong? is there better way?thanks
>
> If you modify a list while you are iterating over it, you may get
> unexpected results (an infinite loop in this case for me). Also ("a" in
> item) will match "aword" since "a" is a component of it. I imagine you
> mean (item == "a").
>
> Try this:
>
> output = []
> for item in data:
>      if item == "d":
>          output.append("dword")
>      output.append(item)
>      if item == "a":
>          output.append("aword")
>
>  >>> output
> ['a', 'aword', 'b', 'c', 'dword', 'd', 'a', 'aword', 'b', 'e', 'dword', 'd']
> --
> Michael Hoffman

Infinite loop for me too! ^_^, should think of it b4 pressing F5.




More information about the Python-list mailing list