You could use a list comprehension to get all indices of Banana
and then slicing to get every second of these indices and then just set the corresponding list item to Pear
:
>>> l = ['Banana', 'Apple', 'John', 'Banana', 'Food', 'Banana']
>>> for idx in [idx for idx, name in enumerate(l) if name == 'Banana'][::2]:
... l[idx] = 'Pear'
>>> l
['Pear', 'Apple', 'John', 'Banana', 'Food', 'Pear']
Instead of a comprehension and slicing you could also use a generator expression and itertools.islice
:
>>> from itertools import islice
>>> l = ['Banana', 'Apple', 'John', 'Banana', 'Food', 'Banana']
>>> for idx in islice((idx for idx, name in enumerate(l) if name == 'Banana'), None, None, 2):
... l[idx] = 'Pear'
>>> l
['Pear', 'Apple', 'John', 'Banana', 'Food', 'Pear']
Another possibility, specifically if you don't want to change your list in-place, would be creating your own generator function:
def replace_every_second(inp, needle, repl):
cnt = 0
for item in inp:
if item == needle: # is it a match?
if cnt % 2 == 0: # is it a second occurence?
yield repl
else:
yield item
cnt += 1 # always increase the counter
else:
yield item
>>> l = ['Banana', 'Apple', 'John', 'Banana', 'Food', 'Banana']
>>> list(replace_every_second(l, 'Banana', 'Pear'))
['Pear', 'Apple', 'John', 'Banana', 'Food', 'Pear']