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]
2
  • you need to replace the part of array from index 2? that is the third parameter? Commented Apr 2, 2017 at 14:24
  • What's your guess? have you searched for proper functions or methods that might be useful for this task? Commented Apr 2, 2017 at 14:24

2 Answers 2

10

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!

Sign up to request clarification or add additional context in comments.

1 Comment

pythonic answer :)
9

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!

5 Comments

this replace the original list!! that is even a is affected!
@Keiwan +1 for using a=a[:]
Yeah, I just noticed and edited. Thank you @Keiwan
That is a very tricky python feature in my opinion!
This is really cool, and is simpler than the accepted answer. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.