yayu
yayu

Reputation: 8088

Replacing an element of a list with multiple values

if I have

l = ['a','b','x','f']

I want to replace 'x' by sub_list = ['c','d','e']

What is the best way to do this? I have,

l = l[:index_x] + sub_list + l[index_x+1:]

Upvotes: 0

Views: 86

Answers (3)

Nasser Al-Shawwa
Nasser Al-Shawwa

Reputation: 3653

An alternative would be to use the insert() method

l        = ['a','b','x','f']
sub_list = ['c','d','e']
ind      = l.index('x')

l.pop(ind)
for item in reversed(sub_list):
    l.insert(ind, item)

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

l = ['a','b','x','f']

sub_list = ['c','d','e']

ind = l.index("x")
l[ind:ind+1] = sub_list

print(l)
['a', 'b', 'c', 'd', 'e', 'f']

If you have a list that has multiple x's using index will replace the first x.

If you wanted to replace all x's:

l = ['a','b','x','f',"x"]
sub_list = ['c','d','e']
for ind, ele in enumerate(l): # use l[:] if the element to be replaced is in sub_list
    if ele == "x":
        l[ind:ind+1] = sub_list
print(l)
['a', 'b', 'c', 'd', 'e', 'f', 'c', 'd', 'e']

Upvotes: 5

Cory Kramer
Cory Kramer

Reputation: 117856

You can find the index of the element you wish to replace, then assign the sublist to a slice of the original list.

def replaceWithSublist(l, sub, elem):
    index = l.index(elem)
    l[index : index+1] = sub
    return l

>>> l = ['a','b','x','f']
>>> sublist = ['c','d','e']

>>> replaceWithSublist(l, sublist, 'x')
['a', 'b', 'c', 'd', 'e', 'f']

Upvotes: 2

Related Questions