Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search for element in list and replace it by multiple items

Tags:

python

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

like image 419
greole Avatar asked Dec 10 '13 16:12

greole


People also ask

How do you replace multiple elements in a list in Python?

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.

How do you replace all occurrences in a list in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

How do you replace elements in a list?

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.

How do you test multiple items in a list?

To select multiple items in a list, hold down the Ctrl (PC) or Command (Mac) key. Then click on your desired items to select.


2 Answers

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.

like image 97
falsetru Avatar answered Sep 19 '22 06:09

falsetru


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']
>>> 
like image 37
karthikr Avatar answered Sep 21 '22 06:09

karthikr