list insertion question

Michael Hoffman at mh391.invalid
Tue Apr 17 03:47:21 CEST 2007

eight02645999 at 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":
     if item == "a":

 >>> output
['a', 'aword', 'b', 'c', 'dword', 'd', 'a', 'aword', 'b', 'e', 'dword', 'd']
Michael Hoffman

More information about the Python-list mailing list