Python: Insert an item in a list every time some other item appears

Viewed 55

Though a process, I expect to have a succession of lists containing strings. Some of those strings will contrain a substring called 'foo'. At all those locations, I would like to insert another string item 'bar' before that.

So if

list1 = ['alpha', 'beta', 'gamma' , 'Donald-foo' , 'omega', 'foo Obama', 'football']

I would liked to create list2 which is

list2 = ['alpha', 'beta', 'gamma' , 'bar', 'Donald-foo' , 'omega', 'bar', 'foo Obama', 'bar', 'football']

So far I have tried this:

list3 = [i for i,s in enumerate(list1) if 'foo' in s]

this gives me

list3 = [3, 5, 6]


for k in reversed(list3):
    list1.insert(k,'bar')

This does the job but feels like a very clunky and painful way to go about it. Is there a more elegant approach?

4 Answers

This would work:

[i for s in [*map(lambda x: (['bar', x] if 'foo' in x else [x]), list1)] for i in s]
['alpha',
 'beta',
 'gamma',
 'bar',
 'Donald-foo',
 'omega',
 'bar',
 'foo Obama',
 'bar',
 'football']

For all items in list1, it's returning ['bar', 'item'] if 'foo' is found, or just ['item'] if it isn't. Then I'm flattening. Here is the unflattened part:

[*map(lambda x: (['bar', x] if 'foo' in x else [x]), list1)]
[['alpha'],
 ['beta'],
 ['gamma'],
 ['bar', 'Donald-foo'],
 ['omega'],
 ['bar', 'foo Obama'],
 ['bar', 'football']]

Here you go:

list2 = []
for item in list1:
    if 'foo' in item:
        list2.append('bar')
    list2.append(item)
print(list2)

## -- End pasted text --
['alpha', 'beta', 'gamma', 'bar', 'Donald-foo', 'omega', 'bar', 'foo Obama', 'bar', 'football']

You can achieve this easily with this:

list1 = ['alpha', 'beta', 'gamma' , 'Donald-foo' , 'omega', 'foo Obama', 'football']
list2 = []

for words in list1:
    if 'foo' in words:
        list2.append('bar')
    list2.append(words)

list2 will be:

list2 = ['alpha', 'beta', 'gamma' , 'bar', 'Donald-foo' , 'omega', 'bar', 'foo Obama', 'bar', 'football']

Another easy way with list comprehension (single line-single loop):

from django.contrib.admin.utils import flatten
list1 = flatten([['bar',x] if 'foo' in x else x for x in list1])

list1
#['alpha', 'beta', 'gamma', 'bar', 'Donald-foo', 'omega', 'bar', 'foo Obama', 'bar', 'football']

simply do a loop where 'foo' exists in x replace x with a ['bar',x] and finally flatten to get rid of extra brackets.

Related