list insertion question
Paul Rubin
http
Mon Apr 16 23:45:51 EDT 2007
eight02645999 at yahoo.com writes:
> 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
As others have said, you're mutating the list while iterating through
it, which can give whacked results. Also, even if you operate on a
copy of the list, that algorithm uses quadratic time because of all
the insertions into the list. These days I like to write in the style
def g():
for w in data:
if 'd' in w: yield 'dword'
yield w
if 'a' in w: yield 'aword'
data = list(g(data))
instead of using list.append as someone else suggested. The iterator
approach is probably a bit slower but can be seen as a bit cleaner,
depending on your stylistic preferences.
More information about the Python-list
mailing list