1

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?

2
  • 2
    do you want to replace every "a" in the list? If the input list is different, should that change what you replace "a" with? Commented Sep 30, 2018 at 17:37
  • yes you are correct. I have modified my example Commented Sep 30, 2018 at 17:38

4 Answers 4

3

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']
Sign up to request clarification or add additional context in comments.

Comments

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']

Comments

0

Use a simple for loop:

l = ["a", "b", "c", "a"]
for i in range(len(l)):
    if l[i] == "a":
        l[i] = "a_1"
        l+=["b_1", "c_1"]

>>> l
['a_1', 'b', 'c', 'a_1', 'b_1', 'c_1', 'b_1', 'c_1']
>>> 

Comments

0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.