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]
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!
Okay, here is another simple way to do this: (Edit: forgot slicing a to copy it into c)
a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
c=a[:]
c[2:5]=b
print(c)
Or, when you want to replace in place:
a = [1,2,3,4,5,6,7,8]
b = ['a','b','c']
a[2:5]=b
print(a)
Hope I helped!