list insertion question

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Tue Apr 17 05:36:25 CEST 2007


On Apr 16, 6:05 pm, 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


Traverse the list from highest index
to lowest index:

data = [ 'a', 'b', 'c', 'd', 'a', 'b', 'e', 'd' ]

print data
for idx, value in reversed(list(enumerate(data))):
    if value == 'a':
        data.insert(idx+1, 'aword')
    elif value == 'd':
        data.insert(idx, 'dword')

print data

# OR

last_idx = len(data) - 1

for idx in range(last_idx+1):
    ridx = last_idx - idx
    if data[ridx] == 'a':
        data.insert(ridx+1, 'aword')
    elif data[ridx] == 'd':
        data.insert(ridx, 'dword')

print data

--
Hope this helps,
Steven




More information about the Python-list mailing list