list insertion question
Michael Hoffman
cam.ac.uk at mh391.invalid
Mon Apr 16 21:47:21 EDT 2007
eight02645999 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
More information about the Python-list
mailing list