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