Home > Enterprise >  Adding a word after every particular word in a list in Python
Adding a word after every particular word in a list in Python

Time:11-22

I'm sorry if my Title seems kinda weird, English is not my first Language and I didn't know how to express myself correctly.

I have a list and I want to add a word every time after a particular word: Example:

list = ['add', 'add', 'ball', 'cup', 'add']

Expected result:

list = ['add','Nice', 'add', 'Nice, 'ball', 'cup', 'add','Nice']

I tried including a:

for word in list:
    if 'add' in word:
        list.insert(((list.index(word)) 1,'Nice')

But my loop keeps adding only on the first 'add', and go eternal.

I tried doing something like this:

for word in list:
    if 'add' in word:
        local = list.index(word)   1
        if list[local] == 'Nice':
            pass
        else:
            list.insert(local,'Nice')

It stops the eternal loop, but the second 'add' doesn't get a 'Nice',
I get a: ['add', 'Nice', 'add', 'ball', 'cup', 'add']

It looks like my "for word in list" only sees a singular 'add'.

CodePudding user response:

Mutating the list you're iterating over easily leads to unexpected results since the internal iterator of the loop has no idea of your modification to the sequence.

Instead, you can create a new list to append output to:

lst = ['add', 'add', 'ball', 'cup', 'add']
output = []
for word in lst:
    output.append(word)
    if word == 'add':
        output.append('Nice')
print(output)

This outputs:

['add', 'Nice', 'add', 'Nice', 'ball', 'cup', 'add', 'Nice']

CodePudding user response:

Here is a very shorthand way to do what you want using sum() (for short lists)...

https://docs.python.org/3/library/functions.html#sum

words = ['add', 'add', 'ball', 'cup', 'add']

sum(([v,'Nice'] if v == 'add' else [v] for v in words), [])

Output is:

['add', 'Nice', 'add', 'Nice', 'ball', 'cup', 'add', 'Nice']

Also see itertools.chain() for longer lists as it is more efficient.

  • Related