5

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]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
user3387666
  • 237
  • 1
  • 3
  • 9

2 Answers2

9

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!

Keerthana Prabhakaran
  • 3,766
  • 1
  • 13
  • 23
8

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!

trashy
  • 166
  • 6