What is the simplest method for replacing one item in a list with two?
So:
list=['t' , 'r', 'g', 'h', 'k']
if I wanted to replace 'r' with 'a' and 'b':
list = ['t' , 'a' , 'b', 'g', 'h', 'k']
Auxiliary Space: O(1), for using constant extra space. Store the element at pos1 and pos2 as a pair in a tuple variable, say get. Unpack those elements with pos2 and pos1 positions in that list. Now, both the positions in that list are swapped.
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.
You can replace items in a Python list using list indexing, a list comprehension, or a for loop. If you want to replace one value in a list, the indexing syntax is most appropriate.
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
It can be done fairly easily with slice assignment:
>>> l = ['t' , 'r', 'g', 'h', 'k']
>>>
>>> pos = l.index('r')
>>> l[pos:pos+1] = ('a', 'b')
>>>
>>> l
['t', 'a', 'b', 'g', 'h', 'k']
Also, don't call your variable list
, since that name is already used by a built-in function.
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