What is the pythonic way to search through the given list ['a', 'b', 'c']
for the element b
replace it and insert multiple items b1, b2, b3
so that the list finally reads as ['a', 'b1', 'b2', 'b3', 'c']
Replace Multiple Values in a Python List. There may be many times when you want to replace not just a single item, but multiple items. This can be done quite simply using the for loop method shown earlier.
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
To select multiple items in a list, hold down the Ctrl (PC) or Command (Mac) key. Then click on your desired items to select.
Using slice notation:
>>> lst = ['a', 'b', 'c']
>>> i = lst.index('b') # This raises ValueError if there's no 'b' in the list.
>>> lst[i:i+1] = 'b1', 'b2', 'b3'
>>> lst
['a', 'b1', 'b2', 'b3', 'c']
NOTE This changes only the first matching item.
Alternate approach: Using itertools.chain.from_iterable
>>> b = ["b1", "b2", "b3"]
>>> a = ['a', 'b', 'c']
>>> a = [b if x=='b' else [x] for x in a]
>>> a
['a', ['b1', 'b2', 'b3'], 'c']
>>> import itertools
>>> list(itertools.chain.from_iterable(a))
['a', 'b1', 'b2', 'b3', 'c']
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With