Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing one item in a list with two items

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']
like image 729
Jasmine078 Avatar asked Mar 10 '14 19:03

Jasmine078


People also ask

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

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.

How do you replace one element 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.

Does replace () work on lists?

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.

How do you use replace in a list?

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 .


1 Answers

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.

like image 119
arshajii Avatar answered Sep 19 '22 03:09

arshajii