Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to replace part of array with another array [duplicate]

I'm looking for the most pythonic way of doing something like that:

a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
c = replace(a,b,2)

c is now [1,2,'a','b','c',6,7,8]
like image 820
user3387666 Avatar asked Dec 11 '22 12:12

user3387666


1 Answers

you can slice your list accordingly!

  • That is, with a and b being your initial list and the one that you want to replace from index s, a[:s] will get all elements before from 0 to s that is ([1,2]).

  • a[s+len(b):] will get all items from index s to len(b), that is ([6,7,8])

so when you concatenate the first result along with b and then the second result you can get the desired output!

a[:s]+b+a[s+len(b):]

So,

>>> a = [1,2,3,4,5,6,7,8]
>>> b = ['a','b','c']
>>> replace=lambda a,b,s:a[:s]+b+a[s+len(b):]
>>> c = replace(a,b,2)
>>> print c
[1, 2, 'a', 'b', 'c', 6, 7, 8]

Hope this helps!

like image 114
Keerthana Prabhakaran Avatar answered Jun 04 '23 04:06

Keerthana Prabhakaran