I have a list ["a","b","c","a"] where I want to replace "a" with ["a_1","b_1","c_1"] such that the list becomes ["a_1","b_1","c_1","b","c", "a_1","b_1","c_1"]
What is the fastest way to do this in python?
You can use a comprehension with chain.from_iterable and a ternary statement:
from itertools import chain
L = list('abca') # ['a', 'b', 'c', 'a']
rep_key, rep_val = ('a', ['a_1', 'b_1', 'c_1'])
res = list(chain.from_iterable([i] if i != rep_key else rep_val for i in L))
['a_1', 'b_1', 'c_1', 'b', 'c', 'a_1', 'b_1', 'c_1']
If you want to mutate your list, then you can rely on slicing. This will indeed replace elements in your list, not create a new one.
lst = ["a", "b", "c", "a"]
a_indices = [i for i, c in enumerate(lst) if c == "a"]
for i in reversed(a_indices):
lst[i:i+1] = ['a_1', 'b_1', 'c_1']
print(lst) # ['a_1', 'b_1', 'c_1', 'b', 'c', 'a_1', 'b_1', 'c_1']
This is a good place for a simple generator function:
def lazy_replace(L, char, val):
for item in L:
if item == char:
yield from val
else:
yield item
>>> L = list('abca')
>>> val = ['a_1', 'b_1', 'c_1']
>>> list(lazy_replace(L, 'a', val))
['a_1', 'b_1', 'c_1', 'b', 'c', 'a_1', 'b_1', 'c_1']
"a"in the list? If the input list is different, should that change what you replace"a"with?